forked from NuGet/NuGet.Client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
421 lines (350 loc) · 15.4 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
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
// 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.
extern alias CoreV2;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using Microsoft.Win32;
using NuGet.Common;
using NuGet.PackageManagement;
namespace NuGet.CommandLine
{
public class Program
{
private const string Utf8Option = "-utf8";
private const string ForceEnglishOutputOption = "-forceEnglishOutput";
#if DEBUG
private const string DebugOption = "--debug";
#endif
private const string OSVersionRegistryKey = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion";
private const string FilesystemRegistryKey = @"SYSTEM\CurrentControlSet\Control\FileSystem";
private const string DotNetSetupRegistryKey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\";
private const int Net462ReleasedVersion = 394802;
private static readonly string ThisExecutableName = typeof(Program).Assembly.GetName().Name;
[Import]
public HelpCommand HelpCommand { get; set; }
[ImportMany]
public IEnumerable<ICommand> Commands { get; set; }
[Import]
public ICommandManager Manager { get; set; }
/// <summary>
/// Flag meant for unit tests that prevents command line extensions from being loaded.
/// </summary>
public static bool IgnoreExtensions { get; set; }
public static int Main(string[] args)
{
AppContext.SetSwitch("Switch.System.IO.UseLegacyPathHandling", false);
AppContext.SetSwitch("Switch.System.IO.BlockLongPaths", false);
#if DEBUG
if (args.Contains(DebugOption, StringComparer.OrdinalIgnoreCase))
{
args = args.Where(arg => !string.Equals(arg, DebugOption, StringComparison.OrdinalIgnoreCase)).ToArray();
System.Diagnostics.Debugger.Launch();
}
#endif
#if IS_DESKTOP
// Find any response files and resolve the args
if (!RuntimeEnvironmentHelper.IsMono)
{
args = CommandLineResponseFile.ParseArgsResponseFiles(args);
}
#endif
return MainCore(Directory.GetCurrentDirectory(), args);
}
public static int MainCore(string workingDirectory, string[] args)
{
// First, optionally disable localization in resources.
if (args.Any(arg => string.Equals(arg, ForceEnglishOutputOption, StringComparison.OrdinalIgnoreCase)))
{
CultureUtility.DisableLocalization();
}
// set output encoding to UTF8 if -utf8 is specified
var oldOutputEncoding = System.Console.OutputEncoding;
if (args.Any(arg => string.Equals(arg, Utf8Option, StringComparison.OrdinalIgnoreCase)))
{
args = args.Where(arg => !string.Equals(arg, Utf8Option, StringComparison.OrdinalIgnoreCase)).ToArray();
SetConsoleOutputEncoding(Encoding.UTF8);
}
// Increase the maximum number of connections per server.
if (!RuntimeEnvironmentHelper.IsMono)
{
ServicePointManager.DefaultConnectionLimit = 64;
}
else
{
// Keep mono limited to a single download to avoid issues.
ServicePointManager.DefaultConnectionLimit = 1;
}
var console = new Console();
var fileSystem = new CoreV2.NuGet.PhysicalFileSystem(workingDirectory);
try
{
// Remove NuGet.exe.old
RemoveOldFile(fileSystem);
// Import Dependencies
var p = new Program();
p.Initialize(fileSystem, console);
// Add commands to the manager
foreach (var cmd in p.Commands)
{
p.Manager.RegisterCommand(cmd);
}
var parser = new CommandLineParser(p.Manager);
// Parse the command
var command = parser.ParseCommandLine(args) ?? p.HelpCommand;
command.CurrentDirectory = workingDirectory;
if (command is Command commandImpl)
{
console.Verbosity = commandImpl.Verbosity;
}
// Fallback on the help command if we failed to parse a valid command
if (!ArgumentCountValid(command))
{
// Get the command name and add it to the argument list of the help command
var commandName = command.CommandAttribute.CommandName;
// Print invalid arguments command error message in stderr
console.WriteError(LocalizedResourceManager.GetString("InvalidArguments"), commandName);
// then show help
p.HelpCommand.ViewHelpForCommand(commandName);
return 1;
}
else
{
SetConsoleInteractivity(console, command as Command);
try
{
command.Execute();
}
catch (CommandLineArgumentCombinationException e)
{
var commandName = command.CommandAttribute.CommandName;
console.WriteLine($"{string.Format(CultureInfo.CurrentCulture, LocalizedResourceManager.GetString("InvalidArguments"), commandName)} {e.Message}");
p.HelpCommand.ViewHelpForCommand(commandName);
return 1;
}
}
}
catch (AggregateException exception)
{
var unwrappedEx = ExceptionUtility.Unwrap(exception);
LogException(unwrappedEx, console);
return 1;
}
catch (ExitCodeException e)
{
return e.ExitCode;
}
catch (PathTooLongException e)
{
LogException(e, console);
if (RuntimeEnvironmentHelper.IsWindows)
{
LogHelperMessageForPathTooLongException(console);
}
return 1;
}
catch (Exception exception)
{
LogException(exception, console);
return 1;
}
finally
{
CoreV2.NuGet.OptimizedZipPackage.PurgeCache();
SetConsoleOutputEncoding(oldOutputEncoding);
}
return 0;
}
private void Initialize(CoreV2.NuGet.IFileSystem fileSystem, IConsole console)
{
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
using (var catalog = new AggregateCatalog(new AssemblyCatalog(GetType().Assembly)))
{
if (!IgnoreExtensions)
{
AddExtensionsToCatalog(catalog, console);
}
try
{
using (var container = new CompositionContainer(catalog))
{
container.ComposeExportedValue(console);
container.ComposeExportedValue<CoreV2.NuGet.IPackageRepositoryFactory>(new CommandLineRepositoryFactory(console));
container.ComposeExportedValue(fileSystem);
container.ComposeParts(this);
}
}
catch (ReflectionTypeLoadException ex) when (ex?.LoaderExceptions.Length > 0)
{
throw new AggregateException(ex.LoaderExceptions);
}
}
}
// This method acts as a binding redirect
private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
var name = new AssemblyName(args.Name);
if (string.Equals(name.Name, ThisExecutableName, StringComparison.OrdinalIgnoreCase))
{
return typeof(Program).Assembly;
}
return null;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We don't want to block the exe from usage if anything failed")]
internal static void RemoveOldFile(CoreV2.NuGet.IFileSystem fileSystem)
{
var oldFile = typeof(Program).Assembly.Location + ".old";
try
{
if (fileSystem.FileExists(oldFile))
{
fileSystem.DeleteFile(oldFile);
}
}
catch
{
// We don't want to block the exe from usage if anything failed
}
}
public static bool ArgumentCountValid(ICommand command)
{
var attribute = command.CommandAttribute;
return command.Arguments.Count >= attribute.MinArgs &&
command.Arguments.Count <= attribute.MaxArgs;
}
private static void AddExtensionsToCatalog(AggregateCatalog catalog, IConsole console)
{
var extensionLocator = new ExtensionLocator();
var files = extensionLocator.FindExtensions();
RegisterExtensions(catalog, files, console);
}
private static void RegisterExtensions(AggregateCatalog catalog, IEnumerable<string> enumerateFiles, IConsole console)
{
foreach (var item in enumerateFiles)
{
AssemblyCatalog assemblyCatalog = null;
try
{
assemblyCatalog = new AssemblyCatalog(item);
// get the parts - throw if something went wrong
var parts = assemblyCatalog.Parts;
// load all the types - throw if assembly cannot load (missing dependencies is a good example)
var assembly = Assembly.LoadFile(item);
assembly.GetTypes();
catalog.Catalogs.Add(assemblyCatalog);
}
catch (BadImageFormatException ex)
{
if (assemblyCatalog != null)
{
assemblyCatalog.Dispose();
}
// Ignore if the dll wasn't a valid assembly
console.WriteWarning(ex.Message);
}
catch (FileLoadException ex)
{
// Ignore if we couldn't load the assembly.
if (assemblyCatalog != null)
{
assemblyCatalog.Dispose();
}
var message =
string.Format(CultureInfo.CurrentCulture, LocalizedResourceManager.GetString(nameof(NuGetResources.FailedToLoadExtension)),
item);
console.WriteWarning(message);
console.WriteWarning(ex.Message);
}
catch (ReflectionTypeLoadException rex)
{
// ignore if the assembly is missing dependencies
var resource =
LocalizedResourceManager.GetString(nameof(NuGetResources.FailedToLoadExtensionDuringMefComposition));
var perAssemblyError = string.Empty;
if (rex?.LoaderExceptions.Length > 0)
{
var builder = new StringBuilder();
builder.AppendLine(string.Empty);
var errors = rex.LoaderExceptions.Select(e => e.Message).Distinct(StringComparer.Ordinal);
foreach (var error in errors)
{
builder.AppendLine(error);
}
perAssemblyError = builder.ToString();
}
var warning = string.Format(CultureInfo.CurrentCulture, resource, item, perAssemblyError);
console.WriteWarning(warning);
}
}
}
private static void SetConsoleInteractivity(IConsole console, Command command)
{
// Apply command setting
console.IsNonInteractive = command.NonInteractive;
// Global environment variable to prevent the exe for prompting for credentials
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("NUGET_EXE_NO_PROMPT")))
{
console.IsNonInteractive = true;
}
// Disable non-interactive if force is set.
var forceInteractive = Environment.GetEnvironmentVariable("FORCE_NUGET_EXE_INTERACTIVE");
if (!string.IsNullOrEmpty(forceInteractive))
{
console.IsNonInteractive = false;
}
}
private static void SetConsoleOutputEncoding(System.Text.Encoding encoding)
{
try
{
System.Console.OutputEncoding = encoding;
}
catch (IOException)
{
}
}
private static void LogException(Exception exception, IConsole console)
{
var logStackAsError = console.Verbosity == Verbosity.Detailed;
ExceptionUtilities.LogException(exception, console, logStackAsError);
}
private static void LogHelperMessageForPathTooLongException(Console logger)
{
if (!IsWindows10(logger))
{
logger.WriteWarning(LocalizedResourceManager.GetString(nameof(NuGetResources.Warning_LongPath_UnsupportedOS)));
}
else if (!IsSupportLongPathEnabled(logger))
{
logger.WriteWarning(LocalizedResourceManager.GetString(nameof(NuGetResources.Warning_LongPath_DisabledPolicy)));
}
else if (!IsRuntimeGreaterThanNet462(logger))
{
logger.WriteWarning(LocalizedResourceManager.GetString(nameof(NuGetResources.Warning_LongPath_UnsupportedNetFramework)));
}
}
private static bool IsWindows10(ILogger logger)
{
var productName = (string)RegistryKeyUtility.GetValueFromRegistryKey("ProductName", OSVersionRegistryKey, Registry.LocalMachine, logger);
return productName != null && productName.StartsWith("Windows 10");
}
private static bool IsSupportLongPathEnabled(ILogger logger)
{
var longPathsEnabled = RegistryKeyUtility.GetValueFromRegistryKey("LongPathsEnabled", FilesystemRegistryKey, Registry.LocalMachine, logger);
return longPathsEnabled != null && (int)longPathsEnabled > 0;
}
private static bool IsRuntimeGreaterThanNet462(ILogger logger)
{
var release = RegistryKeyUtility.GetValueFromRegistryKey("Release", DotNetSetupRegistryKey, Registry.LocalMachine, logger);
return release != null && (int)release >= Net462ReleasedVersion;
}
}
}