private async Task <IEnumerable <string> > Install( DownloadResource downloadResource, PackageIdentity package, PackagePathResolver pathResolver, PackageExtractionContext extractionContext, FrameworkReducer reducer, NuGetFramework framework, string packagesPath, ILogger logger) { var packageResult = await downloadResource.GetDownloadResourceResultAsync( package, new PackageDownloadContext(cache), packagesPath, logger, CancellationToken.None); await PackageExtractor.ExtractPackageAsync( packageResult.PackageSource, packageResult.PackageStream, pathResolver, extractionContext, CancellationToken.None); var libItems = await packageResult.PackageReader.GetLibItemsAsync(CancellationToken.None); var nearest = reducer.GetNearest(framework, libItems.Select(a => a.TargetFramework)); var selected = libItems.Where(a => a.TargetFramework.Equals(nearest)).SelectMany(a => a.Items); return(selected.Where(a => Path.GetExtension(a) == ".dll") .Select(a => Path.Combine(pathResolver.GetInstalledPath(package), a))); }
public static string AddFile(string fileName, IPAddress userIp) { var entry = new DownloadResource(fileName, userIp); resources.Add(entry); return(entry.HashValue); }
/// <summary> /// Download the specified packageId from the NuGet feed. /// </summary> /// <param name="packageId">PackageIdentity to download.</param> /// <returns>Path to the downloaded package.</returns> public virtual async Task <string> DownloadPackageAsync(PackageIdentity packageId) { string downloadPath = Path.Combine(this.downloadFolder, $"{this.feedName}.zip"); PackageDownloadContext packageDownloadContext = new PackageDownloadContext( this.sourceCacheContext, this.downloadFolder, true); DownloadResource downloadResource = await this.sourceRepository.GetResourceAsync <DownloadResource>(); using (DownloadResourceResult downloadResourceResult = await downloadResource.GetDownloadResourceResultAsync( packageId, packageDownloadContext, globalPackagesFolder: string.Empty, logger: this.nuGetLogger, token: CancellationToken.None)) { if (downloadResourceResult.Status != DownloadResourceResultStatus.Available) { throw new Exception("Download of NuGet package failed. DownloadResult Status: {downloadResourceResult.Status}"); } using (FileStream fileStream = File.Create(downloadPath)) { downloadResourceResult.PackageStream.CopyTo(fileStream); } } return(downloadPath); }
private static void CheckUpdate() { _ = Task.Run(() => { Logger.Put(LogPopType.File, LogType.Info, string.Format("The Division 2 Vendor 软件已启动。")); string val = DownloadResource.CheckUpdate().GetAwaiter().GetResult(); if (string.IsNullOrWhiteSpace(val)) { Shower.newestVersion = "更新检查失败,请检查网络设置。"; } else if ("false".Equals(val)) { Shower.newestVersion = "已关闭检查更新功能。"; } else { Shower.newestVersion = "最新版本:" + val; string[] d = val.Substring(1, val.Length - 1).Split("."); try { if (int.Parse(d[0]) > Assembly.GetEntryAssembly().GetName().Version.Major || int.Parse(d[1]) > Assembly.GetEntryAssembly().GetName().Version.Minor) { TitleFunc.updateStr = "【有更新:" + val + "】"; } } catch (Exception) { } } }); }
public async Task <IPackageContent> DownloadAsync(SourceRepository repository, IPackageSearchMetadata package, CancellationToken cancellationToken) { Ensure.NotNull(repository, "repository"); Ensure.NotNull(package, "package"); DownloadResource download = await repository.GetResourceAsync <DownloadResource>(); if (download == null) { throw Ensure.Exception.InvalidOperation($"Unnable to resolve '{nameof(DownloadResource)}'."); } using (var sourceCacheContext = new SourceCacheContext()) { var context = new PackageDownloadContext(sourceCacheContext, Path.GetTempPath(), true); var result = await download.GetDownloadResourceResultAsync(package.Identity, context, String.Empty, nuGetLog, cancellationToken); if (result.Status == DownloadResourceResultStatus.Cancelled) { throw new OperationCanceledException(); } else if (result.Status == DownloadResourceResultStatus.NotFound) { throw Ensure.Exception.InvalidOperation($"Package '{package.Identity.Id}-v{package.Identity.Version}' not found"); } return(new NuGetPackageContent(new PackageArchiveReader(result.PackageStream), log, frameworkFilter)); } }
public override async Task <Tuple <bool, INuGetResource> > TryCreate(SourceRepository source, CancellationToken token) { DownloadResource curResource = null; var serviceIndex = await source.GetResourceAsync <ServiceIndexResourceV3>(token); if (serviceIndex != null) { var httpSourceResource = await source.GetResourceAsync <HttpSourceResource>(token); var client = httpSourceResource.HttpSource; // If index.json contains a flat container resource use that to directly // construct package download urls. var packageBaseAddress = serviceIndex[ServiceTypes.PackageBaseAddress].FirstOrDefault()?.AbsoluteUri; if (packageBaseAddress != null) { curResource = new DownloadResourceV3(client, packageBaseAddress); } else { // If there is no flat container resource fall back to using the registration resource to find // the download url. var registrationResource = await source.GetResourceAsync <RegistrationResourceV3>(token); curResource = new DownloadResourceV3(client, registrationResource); } } return(new Tuple <bool, INuGetResource>(curResource != null, curResource)); }
private int getPercentage(DownloadResource downloadResource) { int percentage = 0; if (downloadResource is MapDownloadResource) { MapDownloadResource mapDownloadResource = (MapDownloadResource)downloadResource; percentage = (int)(((float)mapDownloadResource.NoDownloadedBytes / (mapDownloadResource.getSkmAndZipFilesSize() + mapDownloadResource.getTXGFileSize())) * 100); } return(percentage); }
public async Task TestDownloadResource(string SourceUrl) { SourceRepository repo = GetSourceRepository(SourceUrl); DownloadResource resource = await repo.GetResource <DownloadResource>(); Assert.True(resource != null); Uri downloadMetadata = await resource.GetDownloadUrl(new PackageIdentity("jQuery", new NuGetVersion("1.6.4"))); //*TODOs: Check if the download Url ends with .nupkg. More detailed verification can be added to see if the nupkg file can be fetched from the location. Assert.True(downloadMetadata.OriginalString.EndsWith(".nupkg")); }
public override async Task <Tuple <bool, INuGetResource> > TryCreate(SourceRepository source, CancellationToken token) { DownloadResource DownloadResourceV2 = null; var v2repo = await GetRepository(source, token); if (v2repo != null) { DownloadResourceV2 = new DownloadResourceV2(v2repo); } return(new Tuple <bool, INuGetResource>(DownloadResourceV2 != null, DownloadResourceV2)); }
public override async Task <Tuple <bool, INuGetResource> > TryCreate(SourceRepository source, CancellationToken token) { DownloadResource downloadResource = null; var localResource = await source.GetResourceAsync <FindLocalPackagesResource>(token); if (localResource != null) { downloadResource = new LocalDownloadResource(localResource); } return(new Tuple <bool, INuGetResource>(downloadResource != null, downloadResource)); }
public override Task <Tuple <bool, INuGetResource> > TryCreate(SourceRepository source, CancellationToken token) { DownloadResource resource = null; if ((FeedTypeUtility.GetFeedType(source.PackageSource) & FeedType.HttpV2) != FeedType.None) { var httpSource = HttpSource.Create(source); var parser = new V2FeedParser(httpSource, source.PackageSource); resource = new DownloadResourceV2FeedPrivate(parser, httpSource); } return(Task.FromResult(new Tuple <bool, INuGetResource>(resource != null, resource))); }
private static async Task <Stream> GetDownloadStream(SourceRepository sourceRepository, PackageIdentity packageIdentity, CancellationToken token) { Stream downloadStream = null; DownloadResource downloadResource = await sourceRepository.GetResourceAsync <DownloadResource>(token); if (downloadResource != null) { downloadStream = await downloadResource.GetStream(packageIdentity, token); return(downloadStream); } return(null); }
public override async Task <Tuple <bool, INuGetResource> > TryCreate(SourceRepository source, CancellationToken token) { DownloadResource DownloadResourceV2 = null; if (FeedTypeUtility.GetFeedType(source.PackageSource) == FeedType.FileSystem) { var v2repo = await GetRepository(source, token); if (v2repo != null) { DownloadResourceV2 = new DownloadResourceV2(v2repo); } } return(new Tuple <bool, INuGetResource>(DownloadResourceV2 != null, DownloadResourceV2)); }
/// <summary> /// Downloads the specified packages and returns the files and directories where the package NuGet package lives. /// </summary> /// <param name="packageIdentities">The identity of the packages to find.</param> /// <param name="frameworks">Framework parameter which will force NuGet to evaluate as the specified Framework. If null it will use .NET Standard 2.0.</param> /// <param name="downloadResource">The download resource.</param> /// <param name="getDependencies">If we should get the dependencies.</param> /// <param name="packageFolders">Directories to package folders. Will be lib/build/ref if not defined.</param> /// <param name="packageOutputDirectory">A directory where to store the files, if null a random location will be used.</param> /// <param name="token">A cancellation token.</param> /// <returns>The directory where the NuGet packages are unzipped to. Also the files contained within the requested package only.</returns> private static async Task <InputAssembliesGroup> DownloadPackageFilesAndFolder( IReadOnlyCollection <PackageIdentity> packageIdentities, IReadOnlyCollection <NuGetFramework> frameworks, DownloadResource downloadResource, bool getDependencies = true, IReadOnlyCollection <string>?packageFolders = null, string?packageOutputDirectory = null, CancellationToken token = default) { var librariesToCopy = await GetPackagesToCopy(packageIdentities, downloadResource, frameworks, getDependencies, token).ConfigureAwait(false); packageOutputDirectory ??= GetRandomPackageDirectory(); packageFolders ??= DefaultFoldersToGrab; return(CopyPackageFiles(librariesToCopy, frameworks, packageFolders, packageOutputDirectory, token)); }
public override async Task <Tuple <bool, INuGetResource> > TryCreate(SourceRepository source, CancellationToken token) { DownloadResource resource = null; if (await source.GetFeedType(token) == FeedType.HttpV2) { var serviceDocument = await source.GetResourceAsync <ODataServiceDocumentResourceV2>(token); var httpSource = await source.GetResourceAsync <HttpSourceResource>(token); var parser = new V2FeedParser(httpSource.HttpSource, serviceDocument.BaseAddress, source.PackageSource.Source); resource = new DownloadResourceV2Feed(parser, source.PackageSource.Source); } return(new Tuple <bool, INuGetResource>(resource != null, resource)); }
public async Task TestAllBasicScenariosForLocalShare() { List <PackageIdentity> packages = new List <PackageIdentity>(); packages.Add(new PackageIdentity("Nuget.core", new NuGetVersion("2.8.5"))); packages.Add(new PackageIdentity("Nuget.core", new NuGetVersion("2.5.0"))); //create a local package source by downloading the specific packages from remote feed. SetupLocalShare(packages); //Create source repo based on the local share. string curDir = string.Empty; #if !DNXCORE50 curDir = Environment.CurrentDirectory; #endif SourceRepository repo = GetSourceRepository(curDir); UIMetadataResource resource = repo.GetResource <UIMetadataResource>(); Assert.True(resource != null); //check if UIPackageMetadata works fine. IEnumerable <UIPackageMetadata> packageMetadataList = resource.GetMetadata("Nuget.core", true, true, CancellationToken.None).Result; Assert.True(packageMetadataList != null); Assert.Equal(3, packageMetadataList.Count()); Assert.True(packageMetadataList.All(item => item.Tags.Contains("nuget"))); Assert.True(packageMetadataList.All(item => item.RequireLicenseAcceptance.Equals(false))); Assert.True(packageMetadataList.All(item => item.ProjectUrl.ToString().Equals("http://nuget.codeplex.com/"))); Assert.True(packageMetadataList.Any(item => item.DependencySets.Count() == 1)); Assert.True(packageMetadataList.First(item => item.DependencySets.Count() == 1).DependencySets.First().Packages.Any(item2 => item2.Id.Equals("Microsoft.Web.Xdt", StringComparison.OrdinalIgnoreCase))); //Check if downloadresource works fine. DownloadResource downloadResource = repo.GetResource <DownloadResource>(); Uri downloadUrl = await downloadResource.GetDownloadUrl(new PackageIdentity("Nuget.core", new NuGetVersion("2.5.0"))); Assert.True(downloadUrl.IsFile); Assert.True(File.Exists(downloadUrl.LocalPath)); //path doesnt contain the folder name and also the version is normalized in path for local scenario. //Check if metadata resource works fine. MetadataResource metadataResource = repo.GetResource <MetadataResource>(); NuGetVersion latestVersion = await metadataResource.GetLatestVersion("Nuget.core", true, false, CancellationToken.None); Assert.True(latestVersion.ToNormalizedString().Contains("2.8.5")); }
public void OnInstallStarted(SKToolsDownloadItem currentInstallingItem) { ListItem affectedListItem; if (_activity.codesMap.TryGetValue(currentInstallingItem.ItemCode, out affectedListItem)) { affectedListItem.DownloadResource.DownloadState = SKToolsDownloadItem.Installing; mapsDAO.updateMapResource((MapDownloadResource)affectedListItem.DownloadResource); _activity.RunOnUiThread(() => _activity.adapter.NotifyDataSetChanged()); } else { DownloadResource downloadResource = allMapResources[currentInstallingItem.ItemCode]; downloadResource.DownloadState = (SKToolsDownloadItem.Installing); mapsDAO.updateMapResource((MapDownloadResource)downloadResource); } }
private async Task DownloadNugetPackage(DownloadResource nugetClient, DiscoveryContext context, AddinMetadata package) { var packageFileName = Path.Combine(context.PackagesFolder, $"{package.Name}.{package.NuGetPackageVersion}.nupkg"); if (!File.Exists(packageFileName)) { // Delete prior versions of this package foreach (var f in Directory.EnumerateFiles(context.PackagesFolder, $"{package.Name}.*.nupkg")) { var expectedSplitLength = package.Name.Split('.').Length + package.NuGetPackageVersion.Split('.').Length; var fileName = Path.GetFileNameWithoutExtension(f); if (fileName.Split('.').Length == expectedSplitLength) { File.Delete(f); } } // Download the latest version of the package using var sourceCacheContext = new SourceCacheContext() { NoCache = true }; var downloadContext = new PackageDownloadContext(sourceCacheContext, Path.GetTempPath(), true); var packageIdentity = new PackageIdentity(package.Name, new NuGet.Versioning.NuGetVersion(package.NuGetPackageVersion)); using var result = await nugetClient.GetDownloadResourceResultAsync(packageIdentity, downloadContext, string.Empty, NullLogger.Instance, CancellationToken.None).ConfigureAwait(false); switch (result.Status) { case DownloadResourceResultStatus.Cancelled: throw new OperationCanceledException(); case DownloadResourceResultStatus.NotFound: throw new Exception($"Package '{package.Name} {package.NuGetPackageVersion}' not found"); default: { await using var fileStream = File.OpenWrite(packageFileName); await result.PackageStream.CopyToAsync(fileStream).ConfigureAwait(false); break; } } } }
public NuGetPackageMirrorCommand( bool overwriteExisting, bool includeSymbols, DownloadResource sourceDownloadResource, INuGetSymbolsPackageDownloader symbolsPackageDownloader, NuGetPackageExistenceChecker existenceChecker, NuGetPackagePusher packagePusher, ISettings settings, ILogger logger) { _overwriteExisting = overwriteExisting; _includeSymbols = includeSymbols; _sourceDownloadResource = sourceDownloadResource; _symbolsPackageDownloader = symbolsPackageDownloader; _existenceChecker = existenceChecker; _packagePusher = packagePusher; _settings = settings; _logger = logger; }
private static async Task <IReadOnlyCollection <(DownloadResourceResult downloadResourceResult, PackageIdentity packageIdentity, bool includeFilesInOutput)> > GetPackagesToCopy( IReadOnlyCollection <PackageIdentity> startingPackages, DownloadResource downloadResource, IReadOnlyCollection <NuGetFramework> frameworks, bool getDependencies, CancellationToken token) { var packagesToCopy = new Dictionary <PackageIdentity, (DownloadResourceResult downloadResourceResult, PackageIdentity packageIdentity, bool includeFilesInOutput)>(PackageIdentityNameComparer.Default); var stack = new Stack <(PackageIdentity packageIdentity, bool include)>(startingPackages.Select(x => (x, true))); if (getDependencies) { var supportLibraries = frameworks.SelectMany(x => x.GetSupportLibraries()).ToArray(); if (supportLibraries.Length > 0) { stack.PushRange(supportLibraries.Select(x => (x, false))); } } var processingItems = new (PackageIdentity packageIdentity, bool includeFiles)[ProcessingCount];
private Tuple <String, String> calculateDownloadEstimates(DownloadResource resource, int referencePeriodInSeconds) { long referencePeriod = 1000 * referencePeriodInSeconds; long currentTimestamp = DemoUtils.CurrentTimeMillis(); long downloadPeriod = currentTimestamp - referencePeriod < _activity.downloadStartTime ? currentTimestamp - _activity.downloadStartTime : referencePeriod; long totalBytesDownloaded = 0; var iterator = _activity.downloadChunksMap.GetEnumerator(); do { var entry = iterator.Current; long timestamp = entry.Key; long bytesDownloaded = entry.Value; if (currentTimestamp - timestamp > referencePeriod) { //iterator.remove(); remove current item } else { totalBytesDownloaded += bytesDownloaded; } } while (iterator.MoveNext()); float downloadPeriodSec = downloadPeriod / 1000f; long bytesPerSecond = (long)Math.Round(totalBytesDownloaded / downloadPeriodSec); String formattedTimeLeft = ""; if (totalBytesDownloaded == 0) { formattedTimeLeft = "-"; } else if (resource is MapDownloadResource) { MapDownloadResource mapResource = (MapDownloadResource)resource; long remainingBytes = (mapResource.getSkmAndZipFilesSize() + mapResource.getTXGFileSize()) - mapResource.NoDownloadedBytes; long timeLeft = (downloadPeriod * remainingBytes) / totalBytesDownloaded; formattedTimeLeft = getFormattedTime(timeLeft); } return(new Tuple <string, string>(convertBytesToStringRepresentation(bytesPerSecond) + "/s", formattedTimeLeft)); }
public async Task TestAllResourcesForNonExistentPackage(string SourceUrl) { string packageId = "nonexistentpackage"; string version = "1.0"; SourceRepository repo = GetSourceRepository(SourceUrl); DownloadResource downloadResource = await repo.GetResource <DownloadResource>(); Assert.True(downloadResource != null); Uri downloadMetadata = await downloadResource.GetDownloadUrl(new PackageIdentity(packageId, new NuGetVersion(version))); Assert.True(downloadMetadata == null); MetadataResource metadataResource = await repo.GetResource <MetadataResource>(); Assert.True(metadataResource != null); NuGetVersion latestVersion = await metadataResource.GetLatestVersion(packageId, true, true, CancellationToken.None); Assert.True(latestVersion == null); UIMetadataResource uiMetadataResource = await repo.GetResource <UIMetadataResource>(); Assert.True(uiMetadataResource != null); var result = await uiMetadataResource.GetMetadata(packageId, true, true, CancellationToken.None); Assert.False(result.Any()); DepedencyInfoResource resource = await repo.GetResource <DepedencyInfoResource>(); //Check if we are able to obtain a resource Assert.True(resource != null); List <PackageIdentity> packageIdentities = new List <PackageIdentity>(); packageIdentities.Add(new PackageIdentity(packageId, new NuGetVersion(version))); IEnumerable <PackageDependencyInfo> packages = await resource.ResolvePackages(packageIdentities, NuGet.Frameworks.NuGetFramework.AnyFramework, true, new CancellationToken()); Assert.True(packages == null || packages.Count() == 0); }
public void OnDownloadPaused(SKToolsDownloadItem currentDownloadItem) { _activity.StopPeriodicUpdates(); ListItem affectedListItem; if (_activity.codesMap.TryGetValue(currentDownloadItem.ItemCode, out affectedListItem)) { affectedListItem.DownloadResource.DownloadState = (currentDownloadItem.DownloadState); affectedListItem.DownloadResource.NoDownloadedBytes = (currentDownloadItem.NoDownloadedBytes); mapsDAO.updateMapResource((MapDownloadResource)affectedListItem.DownloadResource); _activity.RunOnUiThread(() => _activity.adapter.NotifyDataSetChanged()); } else { DownloadResource downloadResource = allMapResources[currentDownloadItem.ItemCode]; downloadResource.DownloadState = currentDownloadItem.DownloadState; downloadResource.NoDownloadedBytes = currentDownloadItem.NoDownloadedBytes; mapsDAO.updateMapResource((MapDownloadResource)downloadResource); } _activity.appContext.AppPrefs.SaveDownloadStepPreference(currentDownloadItem.CurrentStepIndex); }
public TypeRetriever( string processingTypeName, string nugetPackageName, MessageMode messageMode, ILog log) { List <Lazy <INuGetResourceProvider> > providers = new List <Lazy <INuGetResourceProvider> >(); providers.AddRange(Repository.Provider.GetCoreV3()); // Add v3 API support var packageSource = new PackageSource(_packageSource); SourceRepository sourceRepository = new SourceRepository(packageSource, providers); _packageMetadataResource = sourceRepository.GetResource <PackageMetadataResource>(); _downloadResource = sourceRepository.GetResource <DownloadResource>(); string workingDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); _downloadDirectory = Path.Combine(workingDir, _libsDir); _packageDownloadContext = new PackageDownloadContext( new SourceCacheContext { NoCache = true, DirectDownload = true, }, _downloadDirectory, true); _nugetLogger = new NugetLogger(log); _nugetPackageName = nugetPackageName; _processingTypeName = processingTypeName; int dotIndex = _processingTypeName.IndexOf('.'); if (dotIndex == -1) { _processingTypeName = $"{_nugetPackageName}.{_processingTypeName}"; } _messageMode = messageMode; }
public override async Task <Tuple <bool, INuGetResource> > TryCreate(SourceRepository source, CancellationToken token) { DownloadResource curResource = null; var serviceIndex = await source.GetResourceAsync <ServiceIndexResourceV3>(token); if (serviceIndex != null) { if (!_cache.TryGetValue(source.PackageSource, out curResource)) { var registrationResource = await source.GetResourceAsync <RegistrationResourceV3>(token); var messageHandlerResource = await source.GetResourceAsync <HttpHandlerResource>(token); var client = new DataClient(messageHandlerResource.MessageHandler); curResource = new DownloadResourceV3(client, registrationResource); _cache.TryAdd(source.PackageSource, curResource); } } return(new Tuple <bool, INuGetResource>(curResource != null, curResource)); }
public void OnDownloadCancelled(string currentDownloadItemCode) { _activity.StopPeriodicUpdates(); ListItem affectedListItem; if (_activity.codesMap.TryGetValue(currentDownloadItemCode, out affectedListItem)) { affectedListItem.DownloadResource.NoDownloadedBytes = (0); affectedListItem.DownloadResource.DownloadState = (SKToolsDownloadItem.NotQueued); activeDownloads.Remove(affectedListItem.DownloadResource); mapsDAO.updateMapResource((MapDownloadResource)affectedListItem.DownloadResource); _activity.RunOnUiThread(() => _activity.adapter.NotifyDataSetChanged()); } else { DownloadResource downloadResource = allMapResources[currentDownloadItemCode]; downloadResource.NoDownloadedBytes = 0; downloadResource.DownloadState = (SKToolsDownloadItem.NotQueued); activeDownloads.Remove(downloadResource); mapsDAO.updateMapResource((MapDownloadResource)downloadResource); } _activity.appContext.AppPrefs.SaveDownloadQueuePreference(activeDownloads); }
public static DownloadResource GetResource(string hashValue) { DownloadResource result = null; List <DownloadResource> outdatedResources = new List <DownloadResource>(); foreach (DownloadResource entry in resources) { // expired? if (DateTime.Now > entry.Expires) { outdatedResources.Add(entry); } else if (entry.HashValue.Equals(hashValue)) { result = entry; } } if (outdatedResources.Count() != 0) { resources.RemoveAll(r => outdatedResources.Contains(r)); } return(result); }
/// <summary> /// Installs packages on any project that targets the dotnet v4. The packages are added to the packages folder /// and the packages.config file and the .csproj file is updated. /// </summary> /// <param name="packageId">The package to install</param> /// <param name="projectTargetVersion">The version of .net framework that the project targets.</param> /// <returns>A completed task of the package installation</returns> internal async Task InstallPackagesOnDotNetV4FrameworkProjects(string packageId, string projectTargetVersion) { using (SourceCacheContext cacheContext = new SourceCacheContext()) { Logger logger = new Logger(this.messageLogger); IEnumerable <SourceRepository> repositories = this.SourceRepositoryProvider.GetRepositories(); HashSet <SourcePackageDependencyInfo> availablePackages = new HashSet <SourcePackageDependencyInfo>(PackageIdentityComparer.Default); NuGetFramework nuGetFramework = NuGetFramework.ParseFolder(projectTargetVersion?.Split('=')[1]); NuGetVersion packageVersion = await GetPackageLatestNugetVersionAsync(packageId, this.SourceRepository, nuGetFramework.DotNetFrameworkName); //get all the package dependencies await GetPackageDependencies( new PackageIdentity(packageId, packageVersion), nuGetFramework, cacheContext, logger, repositories, availablePackages); PackageResolverContext resolverContext = new PackageResolverContext( DependencyBehavior.Lowest, new[] { packageId }, Enumerable.Empty <string>(), Enumerable.Empty <PackageReference>(), Enumerable.Empty <PackageIdentity>(), availablePackages, this.SourceRepositoryProvider.GetRepositories().Select(s => s.PackageSource), logger); PackageResolver resolver = new PackageResolver(); IEnumerable <SourcePackageDependencyInfo> packagesToInstall = resolver.Resolve(resolverContext, CancellationToken.None) .Select(p => availablePackages.Single(x => PackageIdentityComparer.Default.Equals(x, p))); PackagePathResolver packagePathResolver = new PackagePathResolver(this.RootPath); ClientPolicyContext clientPolicyContext = ClientPolicyContext.GetClientPolicy(this.DefaultSettings, logger); PackageExtractionContext packageExtractionContext = new PackageExtractionContext( PackageSaveMode.Defaultv3, XmlDocFileSaveMode.None, clientPolicyContext, logger); foreach (SourcePackageDependencyInfo packageToInstall in packagesToInstall) { PackageReaderBase packageReader; DownloadResourceResult downloadResult = null; string installedPath = packagePathResolver.GetInstalledPath(packageToInstall); if (installedPath == null) { DownloadResource downloadResource = await packageToInstall.Source.GetResourceAsync <DownloadResource>(CancellationToken.None); downloadResult = await downloadResource.GetDownloadResourceResultAsync( packageToInstall, new PackageDownloadContext(cacheContext), SettingsUtility.GetGlobalPackagesFolder(this.DefaultSettings), logger, CancellationToken.None); await PackageExtractor.ExtractPackageAsync( downloadResult.PackageSource, downloadResult.PackageStream, packagePathResolver, packageExtractionContext, CancellationToken.None); installedPath = packagePathResolver.GetInstalledPath(packageToInstall); packageReader = downloadResult.PackageReader; } else { packageReader = new PackageFolderReader(installedPath); } ///update the packages.config file await UpdatePackagesConfigFile(packageToInstall, packageReader, downloadResult, nuGetFramework); UpdateProjectFile(packageReader, installedPath, packageToInstall, nuGetFramework); } } }
private async Task <PluginPackage> GetLatestTemplatePackage(string packageId, string frameworkVersion, IAbsoluteDirectoryPath pluginRepositoryPath) { var nugetFramework = NuGetFramework.ParseFolder(frameworkVersion); ISettings settings = Settings.LoadSpecificSettings(root: null, this.appEnvironment.NuGetConfigFilePath.ToString()); var sourceRepositoryProvider = new SourceRepositoryProvider(new PackageSourceProvider(settings), Repository.Provider.GetCoreV3()); var packageMetaDataList = new List <PluginPackage>(); using (var cacheContext = new SourceCacheContext()) { IEnumerable <SourceRepository> repositories = sourceRepositoryProvider.GetRepositories(); var availablePackages = new HashSet <SourcePackageDependencyInfo>(PackageIdentityComparer.Default); foreach (SourceRepository sourceRepository in repositories) { DependencyInfoResource dependencyInfoResource = await sourceRepository.GetResourceAsync <DependencyInfoResource>().ConfigureAwait(false); IEnumerable <SourcePackageDependencyInfo> dependencyInfo = await dependencyInfoResource.ResolvePackages( packageId, nugetFramework, cacheContext, NullLogger.Instance, CancellationToken.None).ConfigureAwait(false); if (dependencyInfo == null) { continue; } availablePackages.AddRange(dependencyInfo); } var resolverContext = new PackageResolverContext( DependencyBehavior.Highest, new[] { packageId }, Enumerable.Empty <string>(), Enumerable.Empty <PackageReference>(), Enumerable.Empty <PackageIdentity>(), availablePackages, sourceRepositoryProvider.GetRepositories().Select(s => s.PackageSource), NullLogger.Instance); var resolver = new PackageResolver(); try { SourcePackageDependencyInfo packageToInstall = resolver .Resolve(resolverContext, CancellationToken.None).Select(p => availablePackages.Single(x => PackageIdentityComparer.Default.Equals(x, p))) .FirstOrDefault(); var packagePathResolver = new PackagePathResolver(SettingsUtility.GetGlobalPackagesFolder(settings)); var packageExtractionContext = new PackageExtractionContext( PackageSaveMode.Defaultv3, XmlDocFileSaveMode.None, ClientPolicyContext.GetClientPolicy(settings, NullLogger.Instance), NullLogger.Instance); var frameworkReducer = new FrameworkReducer(); string installedPath = packagePathResolver.GetInstalledPath(packageToInstall); PackageReaderBase packageReader; if (installedPath == null && packageToInstall != null) { DownloadResource downloadResource = await packageToInstall.Source .GetResourceAsync <DownloadResource>(CancellationToken.None).ConfigureAwait(false); DownloadResourceResult downloadResult = await downloadResource.GetDownloadResourceResultAsync( packageToInstall, new PackageDownloadContext(cacheContext), SettingsUtility.GetGlobalPackagesFolder(settings), NullLogger.Instance, CancellationToken.None).ConfigureAwait(false); await PackageExtractor.ExtractPackageAsync( downloadResult.PackageSource, downloadResult.PackageStream, packagePathResolver, packageExtractionContext, CancellationToken.None).ConfigureAwait(false); packageReader = downloadResult.PackageReader; } else { packageReader = new PackageFolderReader(installedPath); } PackageIdentity identity = await packageReader.GetIdentityAsync(CancellationToken.None).ConfigureAwait(false); var packageMetaData = new PluginPackage { Name = identity.Id, Version = identity.Version.OriginalVersion, RepositoryPath = pluginRepositoryPath, }; foreach (FrameworkSpecificGroup contentItem in await packageReader.GetContentItemsAsync(CancellationToken.None).ConfigureAwait(false)) { packageMetaData.Plugins.AddRange(contentItem.Items); } var packageFileExtractor = new PackageFileExtractor( packageMetaData.Plugins, XmlDocFileSaveMode.None); await packageReader.CopyFilesAsync( packageMetaData.PluginPath.ToString(), packageMetaData.Plugins, packageFileExtractor.ExtractPackageFile, NullLogger.Instance, CancellationToken.None).ConfigureAwait(false); foreach (IAbsoluteFilePath file in packageMetaData.PluginPath.GetChildDirectoryWithName("content").ChildrenFilesPath) { File.Copy(file.ToString(), Path.Join(packageMetaData.PluginPath.ToString(), file.FileName), overwrite: true); } packageMetaData.Plugins.Clear(); foreach (IAbsoluteFilePath file in packageMetaData.PluginPath.ChildrenFilesPath) { packageMetaData.Plugins.Add(file.GetRelativePathFrom(packageMetaData.PluginPath).ToString()); } Directory.Delete(packageMetaData.PluginPath.GetChildDirectoryWithName("content").ToString(), recursive: true); packageMetaDataList.Add(packageMetaData); } catch (NuGetResolverConstraintException exception) { string foo = exception.Message; } } return(packageMetaDataList.FirstOrDefault()); }
public async Task <IEnumerable <string> > DownloadPackageAndDependenciesAsync(string packageId, string version, string nuGetDir) { List <string> dllsToCopy = new List <string>(); NuGetVersion packageVersion = NuGetVersion.Parse(version); using (SourceCacheContext cacheContext = new SourceCacheContext()) { IEnumerable <SourceRepository> repositories = _sourceRepositoryProvider.GetRepositories(); HashSet <SourcePackageDependencyInfo> availablePackages = new HashSet <SourcePackageDependencyInfo>(PackageIdentityComparer.Default); await GetPackageDependenciesAsync( new PackageIdentity(packageId, packageVersion), _nuGetFramework, cacheContext, _logger, repositories, availablePackages); PackageResolverContext resolverContext = new PackageResolverContext( DependencyBehavior.Lowest, new[] { packageId }, Enumerable.Empty <string>(), Enumerable.Empty <PackageReference>(), Enumerable.Empty <PackageIdentity>(), availablePackages, _sourceRepositoryProvider.GetRepositories().Select(s => s.PackageSource), _logger); PackageResolver resolver = new PackageResolver(); IEnumerable <SourcePackageDependencyInfo> packagesToInstall = resolver.Resolve(resolverContext, CancellationToken.None) .Select(p => availablePackages.Single(x => PackageIdentityComparer.Default.Equals(x, p))); PackagePathResolver packagePathResolver = new PackagePathResolver(nuGetDir); PackageExtractionContext packageExtractionContext = new PackageExtractionContext(PackageSaveMode.Defaultv3, XmlDocFileSaveMode.None, ClientPolicyContext.GetClientPolicy(_settings, _logger), _logger); FrameworkReducer frameworkReducer = new FrameworkReducer(); foreach (SourcePackageDependencyInfo packageToInstall in packagesToInstall) { PackageReaderBase packageReader; string installedPath = packagePathResolver.GetInstalledPath(packageToInstall); if (installedPath == null) { DownloadResource downloadResource = await packageToInstall.Source.GetResourceAsync <DownloadResource>(CancellationToken.None); DownloadResourceResult downloadResult = await downloadResource.GetDownloadResourceResultAsync( packageToInstall, new PackageDownloadContext(cacheContext), SettingsUtility.GetGlobalPackagesFolder(_settings), _logger, CancellationToken.None); await PackageExtractor.ExtractPackageAsync( downloadResult.PackageSource, downloadResult.PackageStream, packagePathResolver, packageExtractionContext, CancellationToken.None); packageReader = downloadResult.PackageReader; installedPath = packagePathResolver.GetInstalledPath(packageToInstall); } else { packageReader = new PackageFolderReader(installedPath); } IEnumerable <FrameworkSpecificGroup> libItems = packageReader.GetLibItems(); NuGetFramework nearest = frameworkReducer.GetNearest(_nuGetFramework, libItems.Select(x => x.TargetFramework)); IEnumerable <string> items = libItems.Where(x => x.TargetFramework.Equals(nearest)).SelectMany(x => x.Items).Where(x => Path.GetExtension(x) == ".dll"); foreach (var item in items) { dllsToCopy.Add(Path.Combine(installedPath, item)); } } } return(dllsToCopy); }