public static async Task <PackageUpdateResource> GetPackageUpdateResource(IPackageSourceProvider sourceProvider, PackageSource packageSource) { var sourceRepositoryProvider = new CachingSourceProvider(sourceProvider); var sourceRepository = sourceRepositoryProvider.CreateRepository(packageSource); return(await sourceRepository.GetResourceAsync <PackageUpdateResource>()); }
private List <SourceRepository> GetEffectiveSourcesCore(ISettings settings, IList <PackageSource> dgSpecSources) { var sourceObjects = dgSpecSources.ToDictionary(k => k.Source, v => v, StringComparer.Ordinal); var packageSourceProvider = new PackageSourceProvider(settings); var packageSourcesFromProvider = packageSourceProvider.LoadPackageSources(); foreach (var sourceUri in Sources) { //DGSpecSources should always match the Sources if (!sourceObjects.ContainsKey(sourceUri)) { Log.LogDebug($"{sourceUri} is in the RestoreArgs Sources but in the passed in dgSpecSources"); sourceObjects[sourceUri] = new PackageSource(sourceUri); } } // Use PackageSource objects from the provider when possible (since those will have credentials from nuget.config) foreach (var source in packageSourcesFromProvider) { if (source.IsEnabled && (sourceObjects.ContainsKey(source.Source))) { sourceObjects[source.Source] = source; } } if (CachingSourceProvider == null) { // Create a shared caching provider if one does not exist already CachingSourceProvider = new CachingSourceProvider(packageSourceProvider); } return(sourceObjects.Select(entry => CachingSourceProvider.CreateRepository(entry.Value)).ToList()); }
private List <SourceRepository> GetEffectiveSourcesCore(ISettings settings) { var sourceObjects = new Dictionary <string, PackageSource>(StringComparer.Ordinal); var packageSourceProvider = new PackageSourceProvider(settings); var packageSourcesFromProvider = packageSourceProvider.LoadPackageSources(); var useNugetConfigSources = (Sources.Count == 0); // Always use passed-in sources and fallback sources foreach (var sourceUri in Enumerable.Concat(Sources, FallbackSources)) { sourceObjects[sourceUri] = new PackageSource(sourceUri); } // Use PackageSource objects from the provider when possible (since those will have credentials from nuget.config) foreach (var source in packageSourcesFromProvider) { if (source.IsEnabled && (useNugetConfigSources || sourceObjects.ContainsKey(source.Source))) { sourceObjects[source.Source] = source; } } if (CachingSourceProvider == null) { // Create a shared caching provider if one does not exist already CachingSourceProvider = new CachingSourceProvider(packageSourceProvider); } return(sourceObjects.Select(entry => CachingSourceProvider.CreateRepository(entry.Value)).ToList()); }
private List <SourceRepository> GetEffectiveSourcesCore(ISettings settings) { // Take the passed in sources var packageSources = new HashSet <string>(Sources, StringComparer.Ordinal); var sourceObjects = new Dictionary <string, PackageSource>(StringComparer.Ordinal); var packageSourceProvider = new Lazy <PackageSourceProvider>(() => new PackageSourceProvider(settings)); // If no sources were passed in use the NuGet.Config sources if (packageSources.Count < 1) { // Add enabled sources foreach (var source in packageSourceProvider.Value.LoadPackageSources()) { if (source.IsEnabled) { sourceObjects[source.Source] = source; } } var enabledSources = sourceObjects.Values .Select(source => source.Source) .Distinct(StringComparer.Ordinal) .ToList(); packageSources.UnionWith(enabledSources); } // Always add fallback sources packageSources.UnionWith(FallbackSources); if (CachingSourceProvider == null) { // Create a shared caching provider if one does not exist already CachingSourceProvider = new CachingSourceProvider(packageSourceProvider.Value); } return(packageSources.Select(sourceUri => { PackageSource source; if (!sourceObjects.TryGetValue(sourceUri, out source)) { source = new PackageSource(sourceUri); } return CachingSourceProvider.CreateRepository(source); }).ToList()); }
public static async Task <SymbolPackageUpdateResourceV3> GetSymbolPackageUpdateResource(IPackageSourceProvider sourceProvider, string source) { // Use a loaded PackageSource if possible since it contains credential info var packageSource = sourceProvider.LoadPackageSources() .Where(e => e.IsEnabled && string.Equals(source, e.Source, StringComparison.OrdinalIgnoreCase)) .FirstOrDefault(); if (packageSource == null) { packageSource = new PackageSource(source); } var sourceRepositoryProvider = new CachingSourceProvider(sourceProvider); var sourceRepository = sourceRepositoryProvider.CreateRepository(packageSource); return(await sourceRepository.GetResourceAsync <SymbolPackageUpdateResourceV3>()); }
private static void Init(ISettings settings) { Dictionary <string, PackageSource> sourceObjects = new Dictionary <string, PackageSource>(StringComparer.Ordinal); PackageSourceProvider packageSourceProvider = new PackageSourceProvider(settings); IEnumerable <PackageSource> packageSourcesFromProvider = packageSourceProvider.LoadPackageSources(); // Use PackageSource objects from the provider when possible (since those will have credentials from nuget.config) foreach (PackageSource source in packageSourcesFromProvider) { if (source.IsEnabled && !sourceObjects.ContainsKey(source.Source)) { sourceObjects[source.Source] = source; } } // Create a shared caching provider if one does not exist already _cachingSourceProvider = _cachingSourceProvider ?? new CachingSourceProvider(packageSourceProvider); List <SourceRepository> repos = sourceObjects.Select(entry => _cachingSourceProvider.CreateRepository(entry.Value)).ToList(); Repos.AddRange(repos); }
private List <SourceRepository> GetEffectiveSourcesCore(ISettings settings, IList <PackageSource> dgSpecSources) { #pragma warning disable CS0618 // Type or member is obsolete var packageSourceProvider = new PackageSourceProvider(settings, enablePackageSourcesChangedEvent: false); #pragma warning restore CS0618 // Type or member is obsolete var packageSourcesFromProvider = packageSourceProvider.LoadPackageSources(); var sourceObjects = new Dictionary <string, PackageSource>(); for (var i = 0; i < dgSpecSources.Count; i++) { sourceObjects[dgSpecSources[i].Source] = dgSpecSources[i]; } foreach (var sourceUri in Sources) { //DGSpecSources should always match the Sources if (!sourceObjects.ContainsKey(sourceUri)) { Log.LogDebug($"{sourceUri} is in the RestoreArgs Sources but not in the passed in dgSpecSources"); sourceObjects[sourceUri] = new PackageSource(sourceUri); } } // Use PackageSource objects from the provider when possible (since those will have credentials from nuget.config) foreach (var source in packageSourcesFromProvider) { if (source.IsEnabled && (sourceObjects.ContainsKey(source.Source))) { sourceObjects[source.Source] = source; } } if (CachingSourceProvider == null) { // Create a shared caching provider if one does not exist already CachingSourceProvider = new CachingSourceProvider(packageSourceProvider); } return(sourceObjects.Select(entry => CachingSourceProvider.CreateRepository(entry.Value)).ToList()); }
public static async Task <PackageUpdateResource> GetPackageUpdateResource(IPackageSourceProvider sourceProvider, string source) { // Use a loaded PackageSource if possible since it contains credential info PackageSource packageSource = null; foreach (var loadedPackageSource in sourceProvider.LoadPackageSources()) { if (loadedPackageSource.IsEnabled && source == loadedPackageSource.Source) { packageSource = loadedPackageSource; break; } } if (packageSource == null) { packageSource = new PackageSource(source); } var sourceRepositoryProvider = new CachingSourceProvider(sourceProvider); var sourceRepository = sourceRepositoryProvider.CreateRepository(packageSource); return(await sourceRepository.GetResourceAsync <PackageUpdateResource>()); }
private async Task <NuGetVersion> GetPackageVersion(VersionRange range) { if (!range.IsFloating) { return(range.MinVersion); } using (var cacheContext = new SourceCacheContext()) { var log = new MSBuildLogger(Log); var defaultSettings = Settings.LoadDefaultSettings(root: null, configFileName: null, machineWideSettings: null); var sourceProvider = new CachingSourceProvider(new PackageSourceProvider(defaultSettings)); var repo = sourceProvider.CreateRepository(new PackageSource(LineupPackageRestoreSource)); var metadata = await repo.GetResourceAsync <MetadataResource>(); if (!await metadata.Exists(LineupPackageId, cacheContext, log, _cts.Token)) { Log.LogError($"Package {LineupPackageId} is not available on '{repo}'"); return(null); } try { var versions = await metadata.GetVersions(LineupPackageId, includePrerelease : true, includeUnlisted : false, sourceCacheContext : cacheContext, log : log, token : _cts.Token); return(range.FindBestMatch(versions)); } catch (Exception ex) { Log.LogError($"Unexpected error while fetching versions from {repo.PackageSource.Source}: " + ex.Message); return(null); } } }
/// <summary> /// Creates new instance of <see cref="BoundRestoreCommandUser"/> with given parameters. /// </summary> /// <param name="nugetSettings">The settings to use.</param> /// <param name="thisFramework">The framework to bind to.</param> /// <param name="runtimeIdentifier">The runtime identifier. Will be used by <see cref="E_NuGetUtils.ExtractAssemblyPaths{TResult}(BoundRestoreCommandUser, LockFile, Func{String, IEnumerable{String}, TResult}, GetFileItemsDelegate, IEnumerable{String})"/> method.</param> /// <param name="runtimeGraph">Optional value indicating runtime graph information: either <see cref="global::NuGet.RuntimeModel.RuntimeGraph"/> directly, or <see cref="String"/> containing package ID of package holding <c>runtime.json</c> file, containing serialized runtime graph definition. If neither is specified, then <c>"Microsoft.NETCore.Platforms"</c> package ID used to locate <c>runtime.json</c> file, as per <see href="https://docs.microsoft.com/en-us/dotnet/core/rid-catalog">official documentation</see>.</param> /// <param name="nugetLogger">The logger to use in restore command.</param> /// <param name="sourceCacheContext">The optional <see cref="SourceCacheContext"/> to use.</param> /// <param name="nuspecCache">The optional <see cref="LocalPackageFileCache"/> to use.</param> /// <param name="clientPolicyContext">The optional <see cref="ClientPolicyContext"/> to use.</param> /// <param name="leaveSourceCacheOpen">Whether to leave the <paramref name="sourceCacheContext"/> open when disposing this <see cref="BoundRestoreCommandUser"/>.</param> /// <param name="lockFileCacheDir">The directory where to store serialized lock files returned by <see cref="RestoreIfNeeded"/>. If <c>null</c> or empty, then <paramref name="lockFileCacheEnvironmentVariableName"/> will be used. Set <paramref name="disableLockFileCacheDir"/> to true to disable caching lock files to file system.</param> /// <param name="lockFileCacheEnvironmentVariableName">The name of the environment variable containing the value for lock file cache directory. If <c>null</c> or empty, then environment variable reading will be skipped. If the environment variable itself is <c>null</c> or empty, then the user's home directory in conjunction with <paramref name="getDefaultLockFileCacheDir"/> will be used to deduce lock file cache directory. Set <paramref name="disableLockFileCacheDir"/> to true to disable caching lock files to file system.</param> /// <param name="getDefaultLockFileCacheDir">This callback will be used when <paramref name="lockFileCacheEnvironmentVariableName"/> is <c>null</c> or empty or when the named environment variable itself was <c>null</c> or empty. This callback will receive current user's home directory as parameter and should return the lock file cache directory. If <c>null</c>, then <see cref="GetDefaultLockFileDir"/> will be used. Set <paramref name="disableLockFileCacheDir"/> to true to disable caching lock files to file system.</param> /// <param name="disableLockFileCacheDir">This variable controls whether the results of <see cref="RestoreIfNeeded"/> will be stored to file system lock file cache directory. By default, the lock file caching is enabled. Set this parameter to <c>true</c> to completely disable caching lock files to file system.</param> /// <exception cref="ArgumentNullException">If <paramref name="nugetSettings"/> is <c>null</c>.</exception> public BoundRestoreCommandUser( ISettings nugetSettings, NuGetFramework thisFramework = null, String runtimeIdentifier = null, EitherOr <RuntimeGraph, String> runtimeGraph = default, ILogger nugetLogger = null, SourceCacheContext sourceCacheContext = null, LocalPackageFileCache nuspecCache = null, ClientPolicyContext clientPolicyContext = null, Boolean leaveSourceCacheOpen = false, String lockFileCacheDir = null, String lockFileCacheEnvironmentVariableName = DEFAULT_LOCK_FILE_CACHE_DIR_ENV_NAME, Func <String, String> getDefaultLockFileCacheDir = null, Boolean disableLockFileCacheDir = false ) { ArgumentValidator.ValidateNotNull(nameof(nugetSettings), nugetSettings); this.ThisFramework = thisFramework ?? NuGetUtility.TryAutoDetectThisProcessFramework(); if (nugetLogger == null) { nugetLogger = NullLogger.Instance; } var global = SettingsUtility.GetGlobalPackagesFolder(nugetSettings); var fallbacks = SettingsUtility.GetFallbackPackageFolders(nugetSettings); if (sourceCacheContext == null) { leaveSourceCacheOpen = false; } var ctx = sourceCacheContext ?? new SourceCacheContext(); var psp = new PackageSourceProvider(nugetSettings); var csp = new CachingSourceProvider(psp); this.RuntimeIdentifier = NuGetUtility.TryAutoDetectThisProcessRuntimeIdentifier(runtimeIdentifier); this._cacheContext = ctx; this._disposeSourceCacheContext = !leaveSourceCacheOpen; this.NuGetLogger = nugetLogger; this._restoreCommandProvider = RestoreCommandProviders.Create( global, fallbacks, new PackageSourceProvider(nugetSettings).LoadPackageSources().Where(s => s.IsEnabled).Select(s => csp.CreateRepository(s)), ctx, nuspecCache ?? new LocalPackageFileCache(), nugetLogger ); this._nugetRestoreRootDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); this._restoreTargetFW = new TargetFrameworkInformation() { FrameworkName = this.ThisFramework }; this.LocalRepositories = this._restoreCommandProvider.GlobalPackages.Singleton() .Concat(this._restoreCommandProvider.FallbackPackageFolders) .ToImmutableDictionary(r => r.RepositoryRoot, r => r); this.RuntimeGraph = new Lazy <RuntimeGraph>(() => { var rGraph = runtimeGraph.GetFirstOrDefault(); if (rGraph == null) { var packageName = runtimeGraph.GetSecondOrDefault(); if (String.IsNullOrEmpty(packageName)) { packageName = DEFAULT_RUNTIME_GRAPH_PACKAGE_ID; } var platformsPackagePath = this.LocalRepositories.Values .SelectMany(r => r.FindPackagesById(packageName)) .OrderByDescending(p => p.Version) .FirstOrDefault() ?.ExpandedPath; rGraph = String.IsNullOrEmpty(platformsPackagePath) ? null : JsonRuntimeFormat.ReadRuntimeGraph(Path.Combine(platformsPackagePath, global::NuGet.RuntimeModel.RuntimeGraph.RuntimeGraphFileName)); } return(rGraph); }, LazyThreadSafetyMode.ExecutionAndPublication); if (!disableLockFileCacheDir) { this.DiskCacheDirectory = lockFileCacheDir .OrIfNullOrEmpty(String.IsNullOrEmpty(lockFileCacheEnvironmentVariableName) ? null : Environment.GetEnvironmentVariable(lockFileCacheEnvironmentVariableName)) .OrIfNullOrEmpty((getDefaultLockFileCacheDir ?? GetDefaultLockFileDir)(Environment.GetEnvironmentVariable( #if NET46 Environment.OSVersion.Platform == PlatformID.Win32NT || Environment.OSVersion.Platform == PlatformID.Win32S || Environment.OSVersion.Platform == PlatformID.Win32Windows || Environment.OSVersion.Platform == PlatformID.WinCE #else System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows) #endif ? "USERPROFILE" : "HOME")) ) .OrIfNullOrEmpty(null); } this._allLockFiles = new ConcurrentDictionary <ImmutableSortedSet <String>, ImmutableDictionary <ImmutableArray <NuGetVersion>, String> >(); this._lockFileFormat = new LockFileFormat(); this._clientPolicyContext = clientPolicyContext ?? ClientPolicyContext.GetClientPolicy(nugetSettings, nugetLogger); }