-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathPackageSourceProvider.cs
More file actions
617 lines (525 loc) · 27.4 KB
/
PackageSourceProvider.cs
File metadata and controls
617 lines (525 loc) · 27.4 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
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
// 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.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace NuGet.Configuration
{
public class PackageSourceProvider : IPackageSourceProvider
{
private const int MaxSupportedProtocolVersion = 3;
private static Lazy<bool> _isMono = new Lazy<bool>(() => Type.GetType("Mono.Runtime") != null);
private ISettings Settings { get; set; }
private readonly IEnumerable<PackageSource> _providerDefaultPrimarySources;
private readonly IEnumerable<PackageSource> _providerDefaultSecondarySources;
private readonly IDictionary<PackageSource, PackageSource> _migratePackageSources;
private readonly IEnumerable<PackageSource> _configurationDefaultSources;
public PackageSourceProvider(ISettings settings)
: this(settings, providerDefaultPrimarySources: null, providerDefaultSecondarySources: null)
{
}
/// <summary>
/// Creates a new PackageSourceProvider instance.
/// </summary>
/// <param name="settings">Specifies the settings file to use to read package sources.</param>
/// <param name="providerDefaultPrimarySources">The primary default sources you would like to use</param>
public PackageSourceProvider(ISettings settings, IEnumerable<PackageSource> providerDefaultPrimarySources)
: this(settings, providerDefaultPrimarySources, providerDefaultSecondarySources: null, migratePackageSources: null)
{
}
/// <summary>
/// Creates a new PackageSourceProvider instance.
/// </summary>
/// <param name="settings">Specifies the settings file to use to read package sources.</param>
/// <param name="providerDefaultPrimarySources">The primary default sources you would like to use</param>
/// <param name="providerDefaultSecondarySources">The secondary default sources you would like to use</param>
public PackageSourceProvider(ISettings settings, IEnumerable<PackageSource> providerDefaultPrimarySources, IEnumerable<PackageSource> providerDefaultSecondarySources)
: this(settings, providerDefaultPrimarySources, providerDefaultSecondarySources, migratePackageSources: null)
{
}
public PackageSourceProvider(
ISettings settings,
IEnumerable<PackageSource> providerDefaultPrimarySources,
IEnumerable<PackageSource> providerDefaultSecondarySources,
IDictionary<PackageSource, PackageSource> migratePackageSources)
{
if (settings == null)
{
throw new ArgumentNullException(nameof(settings));
}
Settings = settings;
Settings.SettingsChanged += (_, __) => { OnPackageSourcesChanged(); };
_providerDefaultPrimarySources = providerDefaultPrimarySources ?? Enumerable.Empty<PackageSource>();
_providerDefaultSecondarySources = providerDefaultSecondarySources ?? Enumerable.Empty<PackageSource>();
_migratePackageSources = migratePackageSources;
_configurationDefaultSources = LoadConfigurationDefaultSources();
}
private IEnumerable<PackageSource> LoadConfigurationDefaultSources()
{
#if !DNXCORE50
// Global default NuGet source doesn't make sense on Mono
if (_isMono.Value)
{
return Enumerable.Empty<PackageSource>();
}
var baseDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "NuGet");
#else
var baseDirectory = Path.Combine(Environment.GetEnvironmentVariable("ProgramData"), "NuGet");
#endif
var settings = new Settings(baseDirectory, ConfigurationContants.ConfigurationDefaultsFile);
var disabledPackageSources = settings.GetSettingValues(ConfigurationContants.DisabledPackageSources);
var packageSources = settings.GetSettingValues(ConfigurationContants.PackageSources);
var packageSourceLookup = new Dictionary<string, IndexedPackageSource>(StringComparer.OrdinalIgnoreCase);
var packageIndex = 0;
foreach (var settingValue in packageSources)
{
// In a SettingValue representing a package source, the Key represents the name of the package source and the Value its source
var isEnabled = !disabledPackageSources.Any(p => p.Key.Equals(settingValue.Key, StringComparison.OrdinalIgnoreCase));
var packageSource = ReadPackageSource(settingValue, isEnabled);
packageSource.IsOfficial = true;
packageIndex = AddOrUpdateIndexedSource(packageSourceLookup, packageIndex, packageSource);
}
return packageSourceLookup.Values
.OrderBy(source => source.Index)
.Select(source => source.PackageSource);
}
/// <summary>
/// Returns PackageSources if specified in the config file. Else returns the default sources specified in the
/// constructor.
/// If no default values were specified, returns an empty sequence.
/// </summary>
public IEnumerable<PackageSource> LoadPackageSources()
{
var settingsValue = new List<SettingValue>();
var sourceSettingValues = Settings.GetSettingValues(ConfigurationContants.PackageSources, isPath: true) ??
Enumerable.Empty<SettingValue>();
// Order the list so that they are ordered in priority order
var settingValues = sourceSettingValues.OrderByDescending(setting => setting.Priority);
// get list of disabled packages
var disabledSetting = Settings.GetSettingValues(ConfigurationContants.DisabledPackageSources) ?? Enumerable.Empty<SettingValue>();
var disabledSources = new Dictionary<string, SettingValue>(StringComparer.OrdinalIgnoreCase);
foreach (var setting in disabledSetting)
{
if (disabledSources.ContainsKey(setting.Key))
{
disabledSources[setting.Key] = setting;
}
else
{
disabledSources.Add(setting.Key, setting);
}
}
var packageSourceLookup = new Dictionary<string, IndexedPackageSource>(StringComparer.OrdinalIgnoreCase);
var packageIndex = 0;
foreach (var setting in settingValues)
{
var name = setting.Key;
var isEnabled = true;
SettingValue disabledSource;
if (disabledSources.TryGetValue(name, out disabledSource)
&&
disabledSource.Priority >= setting.Priority)
{
isEnabled = false;
}
var packageSource = ReadPackageSource(setting, isEnabled);
packageIndex = AddOrUpdateIndexedSource(packageSourceLookup, packageIndex, packageSource);
}
var loadedPackageSources = packageSourceLookup.Values
.OrderBy(source => source.Index)
.Select(source => source.PackageSource)
.ToList();
if (_migratePackageSources != null)
{
MigrateSources(loadedPackageSources);
}
SetDefaultPackageSources(loadedPackageSources);
foreach (var source in loadedPackageSources)
{
source.Description = GetDescription(source);
}
return loadedPackageSources;
}
private PackageSource ReadPackageSource(SettingValue setting, bool isEnabled)
{
var name = setting.Key;
var packageSource = new PackageSource(setting.Value, name, isEnabled)
{
IsMachineWide = setting.IsMachineWide
};
var credentials = ReadCredential(name);
if (credentials != null)
{
packageSource.UserName = credentials.Username;
packageSource.Password = credentials.Password;
packageSource.IsPasswordClearText = credentials.IsPasswordClearText;
}
packageSource.ProtocolVersion = ReadProtocolVersion(setting);
return packageSource;
}
private static int ReadProtocolVersion(SettingValue setting)
{
string protocolVersionString;
int protocolVersion;
if (setting.AdditionalData.TryGetValue(ConfigurationContants.ProtocolVersionAttribute, out protocolVersionString)
&&
int.TryParse(protocolVersionString, out protocolVersion))
{
return protocolVersion;
}
return PackageSource.DefaultProtocolVersion;
}
private static int AddOrUpdateIndexedSource(
Dictionary<string, IndexedPackageSource> packageSourceLookup,
int packageIndex,
PackageSource packageSource)
{
IndexedPackageSource previouslyAddedSource;
if (!packageSourceLookup.TryGetValue(packageSource.Name, out previouslyAddedSource))
{
packageSourceLookup[packageSource.Name] = new IndexedPackageSource
{
PackageSource = packageSource,
Index = packageIndex++
};
}
else if (previouslyAddedSource.PackageSource.ProtocolVersion < packageSource.ProtocolVersion
&&
packageSource.ProtocolVersion <= MaxSupportedProtocolVersion)
{
// Pick the package source with the highest supported protocol version
previouslyAddedSource.PackageSource = packageSource;
}
return packageIndex;
}
// Gets the description of the source if it matches a default source.
// Returns null if it does not match a default source
private string GetDescription(PackageSource source)
{
var matchingSource = _providerDefaultPrimarySources.FirstOrDefault(
s => StringComparer.OrdinalIgnoreCase.Equals(s.Source, source.Source));
if (matchingSource != null)
{
return matchingSource.Description;
}
return null;
}
private PackageSourceCredential ReadCredential(string sourceName)
{
var environmentCredentials = ReadCredentialFromEnvironment(sourceName);
if (environmentCredentials != null)
{
return environmentCredentials;
}
var values = Settings.GetNestedValues(ConfigurationContants.CredentialsSectionName, sourceName);
if (values != null
&& values.Any())
{
var userName = values.FirstOrDefault(k => k.Key.Equals(ConfigurationContants.UsernameToken, StringComparison.OrdinalIgnoreCase)).Value;
if (!String.IsNullOrEmpty(userName))
{
var encryptedPassword = values.FirstOrDefault(k => k.Key.Equals(ConfigurationContants.PasswordToken, StringComparison.OrdinalIgnoreCase)).Value;
if (!String.IsNullOrEmpty(encryptedPassword))
{
return new PackageSourceCredential(userName, EncryptionUtility.DecryptString(encryptedPassword), isPasswordClearText: false);
}
var clearTextPassword = values.FirstOrDefault(k => k.Key.Equals(ConfigurationContants.ClearTextPasswordToken, StringComparison.Ordinal)).Value;
if (!String.IsNullOrEmpty(clearTextPassword))
{
return new PackageSourceCredential(userName, clearTextPassword, isPasswordClearText: true);
}
}
}
return null;
}
private PackageSourceCredential ReadCredentialFromEnvironment(string sourceName)
{
var rawCredentials = Environment.GetEnvironmentVariable("NuGetPackageSourceCredentials_" + sourceName);
if (string.IsNullOrEmpty(rawCredentials))
{
return null;
}
var match = Regex.Match(rawCredentials.Trim(), @"^Username=(?<user>.*?);\s*Password=(?<pass>.*?)$", RegexOptions.IgnoreCase);
if (!match.Success)
{
return null;
}
return new PackageSourceCredential(match.Groups["user"].Value, match.Groups["pass"].Value, true);
}
private void MigrateSources(List<PackageSource> loadedPackageSources)
{
var hasChanges = false;
var packageSourcesToBeRemoved = new List<PackageSource>();
// doing migration
for (var i = 0; i < loadedPackageSources.Count; i++)
{
var ps = loadedPackageSources[i];
PackageSource targetPackageSource;
if (_migratePackageSources.TryGetValue(ps, out targetPackageSource))
{
if (loadedPackageSources.Any(p => p.Equals(targetPackageSource)))
{
packageSourcesToBeRemoved.Add(loadedPackageSources[i]);
}
else
{
loadedPackageSources[i] = targetPackageSource.Clone();
// make sure we preserve the IsEnabled property when migrating package sources
loadedPackageSources[i].IsEnabled = ps.IsEnabled;
}
hasChanges = true;
}
}
foreach (var packageSource in packageSourcesToBeRemoved)
{
loadedPackageSources.Remove(packageSource);
}
if (hasChanges)
{
SavePackageSources(loadedPackageSources);
}
}
private void SetDefaultPackageSources(List<PackageSource> loadedPackageSources)
{
var defaultPackageSourcesToBeAdded = new List<PackageSource>();
if (_configurationDefaultSources == null
|| !_configurationDefaultSources.Any<PackageSource>())
{
// Update provider default sources and use provider default sources since _configurationDefaultSources is empty
UpdateProviderDefaultSources(loadedPackageSources);
defaultPackageSourcesToBeAdded = GetPackageSourcesToBeAdded(loadedPackageSources, _providerDefaultPrimarySources, true);
defaultPackageSourcesToBeAdded = defaultPackageSourcesToBeAdded.Concat(GetPackageSourcesToBeAdded(loadedPackageSources, _providerDefaultSecondarySources, false)).ToList();
}
else
{
defaultPackageSourcesToBeAdded = GetPackageSourcesToBeAdded(loadedPackageSources, _configurationDefaultSources, false);
}
var defaultSourcesInsertIndex = loadedPackageSources.FindIndex(source => source.IsMachineWide);
if (defaultSourcesInsertIndex == -1)
{
defaultSourcesInsertIndex = loadedPackageSources.Count;
}
// Default package sources go ahead of machine wide sources
loadedPackageSources.InsertRange(defaultSourcesInsertIndex, defaultPackageSourcesToBeAdded);
}
private List<PackageSource> GetPackageSourcesToBeAdded(List<PackageSource> loadedPackageSources, IEnumerable<PackageSource> allDefaultPackageSources, bool checkSecondary)
{
// There are 4 different cases to consider for primary/ secondary package sources
// Case 1. primary/ secondary Package Source is already present matching both feed source and the feed name. Set IsOfficial to true
// Case 2. primary/ secondary Package Source is already present matching feed source but with a different feed name. DO NOTHING
// Case 3. primary/ secondary Package Source is not present, but there is another feed source with the same feed name. Override that feed entirely
// Case 4. primary/ secondary Package Source is not present, simply, add it. In addition, if Primary is getting added
// for the first time, promote Primary to Enabled and demote secondary to disabled, if it is already enabled
var defaultPackageSourcesToBeAdded = new List<PackageSource>();
foreach (var packageSource in allDefaultPackageSources)
{
var sourceMatchingIndex = loadedPackageSources.FindIndex(p => p.Source.Equals(packageSource.Source, StringComparison.OrdinalIgnoreCase));
if (sourceMatchingIndex != -1)
{
if (loadedPackageSources[sourceMatchingIndex].Name.Equals(packageSource.Name, StringComparison.CurrentCultureIgnoreCase))
{
// Case 1: Both the feed name and source matches. DO NOTHING except set IsOfficial to true
loadedPackageSources[sourceMatchingIndex].IsOfficial = true;
}
else
{
// Case 2: Only feed source matches but name is different. DO NOTHING
}
}
else
{
var nameMatchingIndex = loadedPackageSources.FindIndex(p => p.Name.Equals(packageSource.Name, StringComparison.CurrentCultureIgnoreCase));
if (nameMatchingIndex != -1)
{
// Case 3: Only feed name matches but source is different. Override it entirely
//DO NOTHING
}
else
{
// Case 4: Default package source is not present. Add it to the temp list. Later, the temp listed is inserted above the machine wide sources
defaultPackageSourcesToBeAdded.Add(packageSource);
packageSource.IsOfficial = true;
}
}
}
return defaultPackageSourcesToBeAdded;
}
private void UpdateProviderDefaultSources(List<PackageSource> loadedSources)
{
// If there are NO other non-machine wide sources, providerDefaultPrimarySource should be enabled
var areProviderDefaultSourcesEnabled = loadedSources.Count == 0 || loadedSources.Where(p => !p.IsMachineWide).Count() == 0
|| loadedSources.Where(p => p.IsEnabled).Count() == 0;
foreach (var packageSource in _providerDefaultPrimarySources)
{
packageSource.IsEnabled = areProviderDefaultSourcesEnabled;
packageSource.IsOfficial = true;
}
//Mark secondary sources as official but not enable them
foreach (var secondaryPackageSource in _providerDefaultSecondarySources)
{
secondaryPackageSource.IsEnabled = false;
secondaryPackageSource.IsOfficial = true;
}
}
public void SavePackageSources(IEnumerable<PackageSource> sources)
{
// clear the old values
// and write the new ones
var sourcesToWrite = sources.Where(s => !s.IsMachineWide && s.IsPersistable);
var existingSettings = (Settings.GetSettingValues(ConfigurationContants.PackageSources, isPath: true) ??
Enumerable.Empty<SettingValue>()).Where(setting => !setting.IsMachineWide).ToList();
existingSettings.RemoveAll(setting => !sources.Any(s => string.Equals(s.Name, setting.Key, StringComparison.OrdinalIgnoreCase)));
var existingSettingsLookup = existingSettings.ToLookup(setting => setting.Key, StringComparer.OrdinalIgnoreCase);
var existingDisabledSources = Settings.GetSettingValues(ConfigurationContants.DisabledPackageSources) ??
Enumerable.Empty<SettingValue>();
var existingDisabledSourcesLookup = existingDisabledSources.ToLookup(setting => setting.Key, StringComparer.OrdinalIgnoreCase);
var sourceSettings = new List<SettingValue>();
var sourcesToDisable = new List<SettingValue>();
foreach (var source in sourcesToWrite)
{
var foundSettingWithSourcePriority = false;
var settingPriority = 0;
var existingSettingForSource = existingSettingsLookup[source.Name];
// Preserve packageSource entries from low priority settings.
foreach (var existingSetting in existingSettingForSource)
{
settingPriority = Math.Max(settingPriority, existingSetting.Priority);
// Write all settings other than the currently written one to the current NuGet.config.
if (ReadProtocolVersion(existingSetting) == source.ProtocolVersion)
{
// Update the source value of all settings with the same protocol version.
existingSetting.Value = source.Source;
foundSettingWithSourcePriority = true;
}
sourceSettings.Add(existingSetting);
}
if (!foundSettingWithSourcePriority)
{
// This is a new source, add it to the Setting with the lowest priority.
var settingValue = new SettingValue(source.Name, source.Source, isMachineWide: false);
if (source.ProtocolVersion != PackageSource.DefaultProtocolVersion)
{
settingValue.AdditionalData[ConfigurationContants.ProtocolVersionAttribute] =
source.ProtocolVersion.ToString(CultureInfo.InvariantCulture);
}
sourceSettings.Add(settingValue);
}
// settingValue contains the setting with the highest priority.
var existingDisabledSettings = existingDisabledSourcesLookup[source.Name];
// Preserve disabledPackageSource entries from low priority settings.
foreach (var setting in existingDisabledSettings.Where(s => s.Priority < settingPriority))
{
sourcesToDisable.Add(setting);
}
if (!source.IsEnabled)
{
// Add an entry to the disabledPackageSource in the file that contains
sourcesToDisable.Add(new SettingValue(source.Name, "true", isMachineWide: false, priority: settingPriority));
}
}
// Write the updates to the nearest settings file.
Settings.UpdateSections(ConfigurationContants.PackageSources, sourceSettings);
// overwrite new values for the <disabledPackageSources> section
Settings.UpdateSections(ConfigurationContants.DisabledPackageSources, sourcesToDisable);
// Overwrite the <packageSourceCredentials> section
Settings.DeleteSection(ConfigurationContants.CredentialsSectionName);
var sourceWithCredentials = sources.Where(s => !String.IsNullOrEmpty(s.UserName) && !String.IsNullOrEmpty(s.Password));
foreach (var source in sourceWithCredentials)
{
Settings.SetNestedValues(ConfigurationContants.CredentialsSectionName, source.Name, new[]
{
new KeyValuePair<string, string>(ConfigurationContants.UsernameToken, source.UserName),
ReadPasswordValues(source)
});
}
OnPackageSourcesChanged();
}
/// <summary>
/// Fires event PackageSourcesChanged
/// </summary>
private void OnPackageSourcesChanged()
{
if (PackageSourcesChanged != null)
{
PackageSourcesChanged(this, EventArgs.Empty);
}
}
private static KeyValuePair<string, string> ReadPasswordValues(PackageSource source)
{
var passwordToken = source.IsPasswordClearText ? ConfigurationContants.ClearTextPasswordToken : ConfigurationContants.PasswordToken;
var passwordValue = source.IsPasswordClearText ? source.Password : EncryptionUtility.EncryptString(source.Password);
return new KeyValuePair<string, string>(passwordToken, passwordValue);
}
public void DisablePackageSource(PackageSource source)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
Settings.SetValue(ConfigurationContants.DisabledPackageSources, source.Name, "true");
}
public bool IsPackageSourceEnabled(PackageSource source)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
var value = Settings.GetValue(ConfigurationContants.DisabledPackageSources, source.Name);
// It doesn't matter what value it is.
// As long as the package source name is persisted in the <disabledPackageSources> section, the source is disabled.
return String.IsNullOrEmpty(value);
}
/// <summary>
/// Gets the name of the ActivePackageSource from NuGet.Config
/// </summary>
public string ActivePackageSourceName
{
get
{
var activeSource = Settings.GetSettingValues(ConfigurationContants.ActivePackageSourceSectionName).FirstOrDefault();
if (activeSource == null)
{
return null;
}
return activeSource.Key;
}
}
/// <summary>
/// Saves the <paramref name="source" /> as the active source.
/// </summary>
/// <param name="source"></param>
public void SaveActivePackageSource(PackageSource source)
{
try
{
Settings.DeleteSection(ConfigurationContants.ActivePackageSourceSectionName);
Settings.SetValue(ConfigurationContants.ActivePackageSourceSectionName, source.Name, source.Source);
}
catch (Exception)
{
// we want to ignore all errors here.
}
}
private class PackageSourceCredential
{
public string Username { get; private set; }
public string Password { get; private set; }
public bool IsPasswordClearText { get; private set; }
public PackageSourceCredential(string username, string password, bool isPasswordClearText)
{
Username = username;
Password = password;
IsPasswordClearText = isPasswordClearText;
}
}
private class IndexedPackageSource
{
public int Index { get; set; }
public PackageSource PackageSource { get; set; }
}
public event EventHandler PackageSourcesChanged;
}
}