public void VersionLength(string version) { // Arrange & Act var semVer = new NuGetVersion(version); Assert.Equal("2.0.0", semVer.ToNormalizedString()); }
public void ParseReadsLegacyStyleVersionNumbers(string versionString, string expectedString) { // Arrange var expected = new NuGetVersion(new Version(expectedString), ""); // Act var actual = NuGetVersion.Parse(versionString); // Assert Assert.Equal(expected.Version, actual.Version); Assert.Equal(expected.Release, actual.Release); }
public IQueryable <V2FeedPackage> GetUpdates( string packageIds, string versions, bool includePrerelease, bool includeAllVersions, string targetFrameworks, string versionConstraints) { if (String.IsNullOrEmpty(packageIds) || String.IsNullOrEmpty(versions)) { return(Enumerable.Empty <V2FeedPackage>().AsQueryable()); } // Workaround https://github.com/NuGet/NuGetGallery/issues/674 for NuGet 2.1 client. Can probably eventually be retired (when nobody uses 2.1 anymore...) // Note - it was URI un-escaping converting + to ' ', undoing that is actually a pretty conservative substitution because // space characters are never acepted as valid by VersionUtility.ParseFrameworkName. if (!string.IsNullOrEmpty(targetFrameworks)) { targetFrameworks = targetFrameworks.Replace(' ', '+'); } var idValues = packageIds.Trim().ToLowerInvariant().Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); var versionValues = versions.Trim().Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); var targetFrameworkValues = String.IsNullOrEmpty(targetFrameworks) ? null : targetFrameworks.Split('|').Select(tfx => NuGetFramework.Parse(tfx)).ToList(); var versionConstraintValues = String.IsNullOrEmpty(versionConstraints) ? new string[idValues.Length] : versionConstraints.Split('|'); if (idValues.Length == 0 || idValues.Length != versionValues.Length || idValues.Length != versionConstraintValues.Length) { // Exit early if the request looks invalid return(Enumerable.Empty <V2FeedPackage>().AsQueryable()); } var versionLookup = idValues.Select((id, i) => { NuGetVersion currentVersion; if (NuGetVersion.TryParse(versionValues[i], out currentVersion)) { VersionRange versionConstraint = null; if (versionConstraintValues[i] != null) { if (!VersionRange.TryParse(versionConstraintValues[i], out versionConstraint)) { versionConstraint = null; } } return(Tuple.Create(id, Tuple.Create(currentVersion, versionConstraint))); } return(null); }) .Where(t => t != null) .ToLookup(t => t.Item1, t => t.Item2, StringComparer.OrdinalIgnoreCase); var packages = PackageRepository.GetAll() .Include(p => p.PackageRegistration) .Include(p => p.SupportedFrameworks) .Where(p => !p.Deleted && p.Listed && (includePrerelease || !p.IsPrerelease) && idValues.Contains(p.PackageRegistration.Id.ToLower())) .OrderBy(p => p.PackageRegistration.Id); return(GetUpdates(packages, versionLookup, targetFrameworkValues, includeAllVersions).AsQueryable() .ToV2FeedPackageQuery(GetSiteRoot(), Configuration.Features.FriendlyLicenses)); }
public static HijackIndexChange SetLatestToTrue(NuGetVersion version) { return(new HijackIndexChange(version, HijackIndexChangeType.SetLatestToTrue)); }
public static HijackIndexChange UpdateMetadata(NuGetVersion version) { return(new HijackIndexChange(version, HijackIndexChangeType.UpdateMetadata)); }
public EnvironmentInspectionResult InspectEnvironment( BoundRestoreCommandUser restorer, String sdkPackageID, String sdkPackageVErsion ) { const String SELF = "self"; var packageID = this._packageID; global::NuGet.Packaging.Core.PackageIdentity selfPackageIdentity = null; var projectFile = this._projectFileLocation; var packageIDIsSelf = this._packageIDIsSelf; var localRepos = restorer.LocalRepositories; var errors = new List <String>(); if (String.IsNullOrEmpty(packageID)) { if (packageIDIsSelf) { // Package ID was specified as self if (String.IsNullOrEmpty(projectFile)) { errors.Add("NMSBT003"); } else { projectFile = Path.GetFullPath(projectFile); // The usage of this task factory comes from the package itself, deduce the package ID selfPackageIdentity = SearchWithinNuGetRepository( projectFile, localRepos .FirstOrDefault(kvp => projectFile.StartsWith(Path.GetFullPath(kvp.Key))) .Value ?.RepositoryRoot ); if (selfPackageIdentity == null) { // Failed to deduce this package ID // No PackageID element and no PackageIDIsSelf element either errors.Add("NMSBT004"); } else { packageID = selfPackageIdentity.Id; } } } else { // No PackageID element and no PackageIDIsSelf element either errors.Add("NMSBT002"); } } else if (packageIDIsSelf) { packageID = null; errors.Add("NMSBT005"); } String packageVersion = null; if (!String.IsNullOrEmpty(packageID)) { packageVersion = this._packageVersion; if ( (String.IsNullOrEmpty(packageVersion) && packageIDIsSelf) || String.Equals(packageVersion, SELF, StringComparison.OrdinalIgnoreCase) ) { // Instead of floating version, we need to deduce our version NuGetVersion deducedVersion = null; if (selfPackageIdentity == null) { // <PackageID> was specified normally, and <PackageVersion> was self var localPackage = localRepos.Values .SelectMany(lr => lr.FindPackagesById(packageID)) .Where(lp => projectFile.StartsWith(lp.ExpandedPath)) .FirstOrDefault(); if (localPackage == null) { errors.Add("NMSBT006"); } else { deducedVersion = localPackage.Version; } } else { // <PackageIDIsSelf> was specified, and no version was specified deducedVersion = selfPackageIdentity.Version; } packageVersion = deducedVersion?.ToNormalizedString(); } } return(new EnvironmentInspectionResult() { ThisFramework = restorer.ThisFramework.ToString(), ThisRuntimeID = restorer.RuntimeIdentifier, SDKPackageID = sdkPackageID, SDKPackageVersion = sdkPackageVErsion, PackageID = packageID, PackageVersion = packageVersion, Errors = errors.ToArray() }); }
public static NuGetVersion Prepend(this NuGetVersion version, string releaseLabel) { return(new NuGetVersion(version.Major, version.Minor, version.Patch, version.Revision, new[] { releaseLabel }.Concat(version.ReleaseLabels), version.Metadata)); }
public async Task DotnetToolTests_ToolRestoreWithRuntimeIdentiferGraphPath_SucceedsAsync() { using (var pathContext = new SimpleTestPathContext()) { string testDirectory = pathContext.WorkingDirectory; var tfm = "netcoreapp2.0"; var projectName = "ToolRestoreProject"; var workingDirectory = Path.Combine(testDirectory, projectName); var packageSource = Path.Combine(testDirectory, "packageSource"); var rid = "win-x64"; var packageRid = "win"; var packageName = string.Join("ToolPackage-", tfm, rid); var packageVersion = NuGetVersion.Parse("1.0.0"); var packages = new List <PackageIdentity>() { new PackageIdentity(packageName, packageVersion) }; var package = new SimpleTestPackageContext(packageName, packageVersion.OriginalVersion); package.Files.Clear(); package.AddFile($"tools/{tfm}/{packageRid}/a.dll"); package.AddFile($"tools/{tfm}/{packageRid}/Settings.json"); package.PackageType = PackageType.DotnetTool; package.UseDefaultRuntimeAssemblies = false; package.PackageTypes.Add(PackageType.DotnetTool); await SimpleTestPackageUtility.CreatePackagesAsync(packageSource, package); _msbuildFixture.CreateDotnetToolProject(testDirectory, projectName, tfm, rid, packageSource, packages); // set up rid graph var ridGraphPath = Path.Combine(testDirectory, "runtime.json"); File.WriteAllBytes(ridGraphPath, GetTestUtilityResource("runtime.json")); using (var stream = File.Open(Path.Combine(workingDirectory, projectName + ".csproj"), FileMode.Open, FileAccess.ReadWrite)) { var xml = XDocument.Load(stream); ProjectFileUtils.AddProperty( xml, "RuntimeIdentifierGraphPath", ridGraphPath); ProjectFileUtils.WriteXmlToFile(xml, stream); } // Act var result = _msbuildFixture.RestoreToolProject(workingDirectory, projectName, string.Empty); // Assert Assert.True(result.ExitCode == 0, result.AllOutput); // Verify the assets file var lockFile = LockFileUtilities.GetLockFile(Path.Combine(testDirectory, projectName, "project.assets.json"), NullLogger.Instance); Assert.NotNull(lockFile); Assert.Equal(2, lockFile.Targets.Count); var ridTargets = lockFile.Targets.Where(e => e.RuntimeIdentifier != null ? e.RuntimeIdentifier.Equals(rid, StringComparison.CurrentCultureIgnoreCase) : false); Assert.Equal(1, ridTargets.Count()); var toolsAssemblies = ridTargets.First().Libraries.First().ToolsAssemblies; Assert.Equal(2, toolsAssemblies.Count); Assert.True(toolsAssemblies.Contains($"tools/{tfm}/{packageRid}/a.dll")); Assert.True(toolsAssemblies.Contains($"tools/{tfm}/{packageRid}/Settings.json")); } }
protected override async Task OkAsync() { if (InstalledPackages.Count > 0) { await InstalledPackages.Select(p => NugetHelper.EnsurePackageInstalled(p.Name, NuGetVersion.Parse(p.Version))) .WhenAll() .ConfigureAwait(false) ; } await base.OkAsync(); }
public async Task <IReadOnlyCollection <ChangeSet> > GetChangeSets(IRepositorySource ops) { _log.WriteLine("Fetching project files"); var projectFiles = await ops.GetProjectFiles(); var allPackages = projectFiles.SelectMany(x => x.ListPackages()).Select(x => x.Key).Distinct().ToArray(); _log.WriteLine("Fetching latest packages"); var nugetPackages = await Task.WhenAll(_nugetApis.Select(x => x.GetPackageVersions(allPackages, AllowBetaPackages))); var latestPackageVersions = nugetPackages .SelectMany(x => x) .GroupBy(x => x.Key) .ToDictionary(x => x.Key, x => x.OrderByDescending(y => y.Value.Version).FirstOrDefault().Value); HashSet <string> packagesToUpdate = new HashSet <string>(); var packages = projectFiles.SelectMany(x => x.ListPackages()) .GroupBy(x => x.Key) .ToDictionary(x => x.Key, x => x.First().Value); foreach (var item in latestPackageVersions) { var projectVersion = NuGetVersion.Parse(packages[item.Key]); var lastVersion = item.Value; if (lastVersion.Version > projectVersion) { // Major minor versions older than 21 days var shouldUpdateMajorMinor = (lastVersion.Version.Major > projectVersion.Major || lastVersion.Version.Minor > projectVersion.Minor) && lastVersion.Released <= DateTime.Now.AddDays(-PackagesMustBePublishedForThisManyDays); var shouldUpdatePatch = lastVersion.Version.Major == projectVersion.Major && lastVersion.Version.Minor == projectVersion.Minor && lastVersion.Version > projectVersion; if (shouldUpdateMajorMinor || shouldUpdatePatch) { packagesToUpdate.Add($"{item.Key}|{item.Value.Version}"); } } } var packageGroupings = packagesToUpdate .Select(x => x.Split('|')) .GroupBy(x => PackageGroupings.Select(y => y.GetGroupName(x[0], x[1])).First(y => y != null), x => x[0]); var changeSets = new List <ChangeSet>(); foreach (var group in packageGroupings) { var message = new StringBuilder($"Auto-update for packages related to '{@group.Key}'"); message.AppendLine(); message.AppendLine(); var groupChangeSet = new ChangeSet { BranchName = $"refs/heads/auto-nuget-update/{@group.Key.ToLowerInvariant()}", }; foreach (var package in @group) { var packageUpdateMessage = $"Updates package '{package}' to version '{latestPackageVersions[package].Version}'"; if (@group.Count() == 1) { message = new StringBuilder(packageUpdateMessage); } else { message.AppendLine(packageUpdateMessage); } foreach (var projectFile in projectFiles) { projectFile.UpdatePackageReference(package, latestPackageVersions[package].Version.ToString()); } } foreach (var projectFile in projectFiles) { var change = projectFile.ToChange(); if (change != null) { groupChangeSet.Changes.Add(change); } projectFile.Reset(); } groupChangeSet.Message = message.ToString(); changeSets.Add(groupChangeSet); } return(changeSets); }
public RunStatus AddPackage(string projectPath, string packageName, string frameworkName, NuGetVersion version) { string projectName = _fileSystem.Path.GetFileName(projectPath); string[] arguments = new[] { "add", $"\"{projectName}\"", "package", packageName, "-v", version.ToString(), "-f", $"\"{frameworkName}\"" }; return(_dotNetRunner.Run(_fileSystem.Path.GetDirectoryName(projectPath), arguments)); }
public void ParseThrowsIfStringIsNullOrEmpty() { ExceptionAssert.ThrowsArgNullOrEmpty(() => NuGetVersion.Parse(null), "value"); ExceptionAssert.ThrowsArgNullOrEmpty(() => NuGetVersion.Parse(String.Empty), "value"); }
public void NuGetVersionKeepsOriginalVersionString(string originalVersion) { var version = new NuGetVersion(originalVersion); Assert.Equal(originalVersion, version.OriginalVersion); }
public void EqualsIsTrueForEmptyRevision() { NuGetVersion.Parse("1.0.0.0").Equals(SemanticVersion.Parse("1.0.0")).Should().BeTrue(); SemanticVersion.Parse("1.0.0").Equals(NuGetVersion.Parse("1.0.0.0")).Should().BeTrue(); }
public void ParseThrowsIfStringIsNotAValidSemVer(string versionString) { ExceptionAssert.ThrowsArgumentException(() => NuGetVersion.Parse(versionString), "value", String.Format(CultureInfo.InvariantCulture, "'{0}' is not a valid version string.", versionString)); }
public void ParseIgnoresLeadingAndTrailingWhitespace(string versionString, string expectedString, string releaseString) { // Arrange var expected = new NuGetVersion(new Version(expectedString), releaseString); // Act var actual = NuGetVersion.Parse(versionString); // Assert Assert.Equal(expected.Version, actual.Version); Assert.Equal(expected.Release, actual.Release); }
public void ToStringFromStringFormat(string versionString, string specialVersion, string expected) { // Arrange var version = new Version(versionString); // Act var semVer = new NuGetVersion(version, specialVersion); // Assert Assert.Equal(expected, String.Format("{0}", semVer)); }
private static async Task <IActionResult> RunInternalAsync( HttpRequest request, string typeName, string typeNamespace, ILogger log) { // Fetch parameters var allowPrerelease = ParseQuery(request.Query, "allowPrerelease", false); var latestVersion = ParseQuery(request.Query, "latestVersion", true); var page = ParseQuery(request.Query, "pageIndex", 0); // Build query var searchText = !string.IsNullOrEmpty(typeName) ? $"typeNames:.{typeName}" : $"typeNames:{typeNamespace}."; // Search var indexClient = SearchServiceClient.Indexes.GetClient(Constants.SearchServiceIndexName); log.LogInformation("Performing search for {searchText}...", searchText); var resultsCollector = new HashSet <PackageDocument>(latestVersion ? PackageDocumentEqualityComparer.ByPackageId : PackageDocumentEqualityComparer.ByPackageIdAndVersion); await indexClient.Documents.ForEachAsync <PackageDocument>(searchText, documentResult => { var isPreRelease = documentResult.Document.IsPreRelease.HasValue && documentResult.Document.IsPreRelease.Value; if (allowPrerelease || !isPreRelease) { resultsCollector.Add(documentResult.Document); } return(resultsCollector.Count <= MaxResults); }, new SearchParameters { Filter = "isListed eq true" + (!allowPrerelease ? " and isPreRelease eq false" : ""), OrderBy = new List <string> { "search.score() desc", "packageVersion desc" }, QueryType = QueryType.Full }); log.LogInformation("Finished performing search for {searchText}. Total results: {totalResults} (page: {page})", searchText, resultsCollector.Count, page); // Build result var result = new FindTypeApiResult(); result.TotalResults = resultsCollector.Count; result.PageIndex = page; result.PageSize = PageSize; result.TotalPages = (long)Math.Ceiling((decimal)(resultsCollector.Count / PageSize) + 1); foreach (var searchResult in resultsCollector.Take(PageSize)) { var nugetVersion = NuGetVersion.Parse(searchResult.PackageVersion); var resultItem = new FindTypeApiPackage { Id = searchResult.PackageId, Version = nugetVersion.ToNormalizedString(), VersionId = 1, Title = searchResult.Title, Authors = searchResult.Authors, Description = searchResult.Summary, Downloads = searchResult.DownloadCount, IconUrl = !string.IsNullOrEmpty(searchResult.IconUrl) ? searchResult.IconUrl : Constants.NuGetPackageDefaultIconUrl, LicenseUrl = searchResult.LicenseUrl, ProjectUrl = searchResult.ProjectUrl, Published = searchResult.Published, Tags = (searchResult.Tags ?? "").Split(' ').ToList(), IsPreRelease = nugetVersion.IsPrerelease, IsLastPreRelease = nugetVersion.IsPrerelease, IsLastRelease = !nugetVersion.IsPrerelease }; foreach (var targetFramework in searchResult.TargetFrameworks) { var framework = NuGetFramework.Parse(targetFramework, FrameworkNameProvider); resultItem.Match.Platforms.Add(framework.DotNetFrameworkName); } foreach (var searchResultTypeName in searchResult.TypeNames) { var resultNamespace = searchResultTypeName.SubstringUntilLast("."); var resultType = searchResultTypeName.SubstringAfterLast("."); if (!string.IsNullOrEmpty(resultNamespace)) { resultItem.Match.Assemblies.Add(resultNamespace); if (!string.IsNullOrEmpty(typeName) && resultType.Equals(typeName, StringComparison.OrdinalIgnoreCase)) { resultItem.Match.TypeNames.Add(new FindTypeApiMatchTypeName { Kind = 0, Namespace = resultNamespace, Name = resultType }); } else if (!string.IsNullOrEmpty(typeNamespace) && resultNamespace.Equals(typeNamespace, StringComparison.OrdinalIgnoreCase)) { resultItem.Match.TypeNames.Add(new FindTypeApiMatchTypeName { Kind = 0, Namespace = resultNamespace }); } } } if (resultItem.Match.TypeNames.Count > 0) { result.Packages.Add(resultItem); } } return(new OkObjectResult(result)); }
public static NuGetVersion RemoveRevision(this NuGetVersion version) { return(new NuGetVersion(version.Major, version.Minor, version.Patch, 0, version.ReleaseLabels, version.Metadata)); }
public SimplePackageId(string packageId, SVersion v) { PackageIdentity = new PackageIdentity(packageId, NuGetVersion.Parse(v.ToString())); Version = v; }
public async Task <InternalNuGetCompatibilityResult> CheckCompatibilityAsync(string packageName, string version, string targetFramework, IEnumerable <SourceRepository> internalRepositories) { if (packageName == null || targetFramework == null || internalRepositories == null) { var invalidParamNames = new List <string>(); if (packageName == null) { invalidParamNames.Add(nameof(packageName)); } if (targetFramework == null) { invalidParamNames.Add(nameof(targetFramework)); } if (internalRepositories == null) { invalidParamNames.Add(nameof(internalRepositories)); } throw new ArgumentException($"Invalid parameter(s) found. The following parameters " + $"cannot be null: {string.Join(", ", invalidParamNames)}"); } string tmpPath = Path.GetTempPath(); var framework = NuGetFramework.Parse(targetFramework); var package = new PackageIdentity(packageName, NuGetVersion.Parse(version)); // Get package information from Nuget SourcePackageDependencyInfo packageSource = null; foreach (var sourceRepository in internalRepositories) { var dependencyInfoResource = await sourceRepository.GetResourceAsync <DependencyInfoResource>(); packageSource = await dependencyInfoResource.ResolvePackage( package, framework, _cacheContext, NullLogger.Instance, CancellationToken.None); if (packageSource != null) { break; } } if (packageSource == null) { var errorMessage = $"Error: No package source found for {package}."; _logger.LogError(errorMessage); var innerException = new PackageSourceNotFoundException(errorMessage); throw new PortingAssistantClientException(ExceptionMessage.PackageSourceNotFound(package), innerException); } // Download package var downloadResource = await packageSource.Source.GetResourceAsync <DownloadResource>(); var downloadResult = await downloadResource.GetDownloadResourceResultAsync( packageSource, new PackageDownloadContext(_cacheContext), Path.Combine(tmpPath), NullLogger.Instance, CancellationToken.None); var packageReader = downloadResult.PackageReader; var nuspecReader = packageReader.NuspecReader; var dependencies = nuspecReader.GetDependencyGroups(); var dependencyPackages = dependencies .SelectMany(d => d.Packages) .Select(p => p.Id) .ToList(); // Gather dlls var frameworkReducer = new FrameworkReducer(); var libItems = packageReader.GetLibItems(); var nearestTargetFrameworks = libItems .Select(li => frameworkReducer.GetNearest( framework, new List <NuGetFramework> { li.TargetFramework })) .ToList(); var isCompatible = libItems.Any() ? nearestTargetFrameworks.Any(nugetFramework => nugetFramework != null) : frameworkReducer.GetNearest(framework, packageReader.GetSupportedFrameworks()) != null; var compatibleDlls = libItems .Where(li => nearestTargetFrameworks.Contains(li.TargetFramework)) .SelectMany(li => li.Items) .Where(s => s.EndsWith("dll", StringComparison.OrdinalIgnoreCase)) .ToList(); var incompatibleDlls = libItems .SelectMany(li => li.Items) .Where(s => !compatibleDlls.Contains(s) && s.EndsWith("dll", StringComparison.OrdinalIgnoreCase)) .ToList(); return(new InternalNuGetCompatibilityResult { IncompatibleDlls = incompatibleDlls, CompatibleDlls = compatibleDlls, IsCompatible = isCompatible, DependencyPackages = dependencyPackages, Source = packageSource.Source.PackageSource.Name }); }
public void PackagesConfigWriter_Duplicate() { var stream = new MemoryStream(); using (PackagesConfigWriter writer = new PackagesConfigWriter(stream)) { writer.WritePackageEntry("packageA", NuGetVersion.Parse("1.0.1"), NuGetFramework.Parse("net45")); Assert.Throws <PackagingException>(() => writer.WritePackageEntry("packageA", NuGetVersion.Parse("2.0.1"), NuGetFramework.Parse("net4"))); } }
private HijackIndexChange(NuGetVersion version, HijackIndexChangeType type) { Version = version ?? throw new ArgumentNullException(nameof(version)); Type = type; }
public string GetRegistrationPageUrl(string id, NuGetVersion lower, NuGetVersion upper) { // BaGet does not support paging the registration resource. throw new NotImplementedException(); }
public static HijackIndexChange Delete(NuGetVersion version) { return(new HijackIndexChange(version, HijackIndexChangeType.Delete)); }
public static async Task <bool> RunAsync(LocalSettings settings, ISleetFileSystem source, string packageId, string version, string reason, bool force, ILogger log) { var success = true; var token = CancellationToken.None; var now = DateTimeOffset.UtcNow; log.LogMinimal($"Reading feed {source.BaseURI.AbsoluteUri}"); // Check if already initialized using (var feedLock = await SourceUtility.VerifyInitAndLock(settings, source, log, token)) { // Validate source await UpgradeUtility.EnsureFeedVersionMatchesTool(source, log, token); // Get sleet.settings.json var sourceSettings = await FeedSettingsUtility.GetSettingsOrDefault(source, log, token); // Settings context used for all operations var context = new SleetContext() { LocalSettings = settings, SourceSettings = sourceSettings, Log = log, Source = source, Token = token }; var packageIndex = new PackageIndex(context); var packages = new List <PackageIdentity>(); if (!string.IsNullOrEmpty(version)) { // Delete a single version of the package var packageVersion = NuGetVersion.Parse(version); packages.Add(new PackageIdentity(packageId, packageVersion)); } else { // Delete all versions of the package packages.AddRange(await packageIndex.GetPackagesByIdAsync(packageId)); } if (string.IsNullOrEmpty(reason)) { reason = string.Empty; } foreach (var package in packages) { var exists = await packageIndex.Exists(package); var symbolsExists = await packageIndex.SymbolsExists(package); if (!exists && !symbolsExists) { log.LogInformation($"{package.ToString()} does not exist."); if (force) { // ignore failures continue; } else { throw new InvalidOperationException($"Package does not exists: {package.ToString()}"); } } var message = $"Removing {package.ToString()}"; if (exists && symbolsExists) { message = $"Removing {package.ToString()} and symbols package for {package.ToString()}"; } else if (symbolsExists) { message = $"Removing symbols package {package.ToString()}"; } await log.LogAsync(LogLevel.Information, message); await SleetUtility.RemovePackage(context, package); } // Save all log.LogMinimal($"Committing changes to {source.BaseURI.AbsoluteUri}"); success &= await source.Commit(log, token); } if (success) { log.LogMinimal($"Successfully deleted packages."); } else { log.LogError($"Failed to delete packages."); } return(success); }
public async Task GetPackageWithDependencies() { var packageService = server.Host.Services.GetRequiredService <IPackageService>(); var result = await packageService.AddAsync(new Package() { Id = "Dummy", Title = "Dummy", Listed = true, Version = NuGetVersion.Parse("1.0.0"), Authors = new [] { "Anton Setiawan" }, LicenseUrl = new Uri("https://github.com/antonmaju/dummy/blob/master/LICENSE"), MinClientVersion = null, Published = DateTime.Parse("1900-01-01T00:00:00"), Dependencies = new List <Core.Entities.PackageDependency>() { new Core.Entities.PackageDependency() { Id = "Consul", VersionRange = "[0.7.2.6, )", TargetFramework = ".NETStandard2.0" } } }); Assert.Equal(PackageAddResult.Success, result); var found = await packageService.FindOrNullAsync(new NuGet.Packaging.Core.PackageIdentity("dummy", NuGetVersion.Parse("1.0.0")), false, true); Assert.NotNull(found.Dependencies); Assert.NotEmpty(found.Dependencies); var one = found.Dependencies.Single(); Assert.Equal("Consul", one.Id); Assert.Equal("[0.7.2.6, )", one.VersionRange); }
public static string ToNormalizedStringSafe(this NuGetVersion self) { return(self != null?self.ToNormalizedString() : String.Empty); }
/// <summary> /// Parse an entry into a V2FeedPackageInfo /// </summary> private V2FeedPackageInfo ParsePackage(string id, XElement element, MetadataReferenceCache metadataCache) { var properties = element.Element(_xnameProperties); var idElement = properties.Element(_xnameId); var titleElement = element.Element(_xnameTitle); // If 'Id' element exist, use its value as accurate package Id // Otherwise, use the value of 'title' if it exist // Use the given Id as final fallback if all elements above don't exist var identityId = metadataCache.GetString(idElement?.Value ?? titleElement?.Value ?? id); var versionString = properties.Element(_xnameVersion).Value; var version = metadataCache.GetVersion(metadataCache.GetString(versionString)); var downloadUrl = metadataCache.GetString(element.Element(_xnameContent).Attribute("src").Value); var title = metadataCache.GetString(titleElement?.Value); var summary = metadataCache.GetString(GetString(element, _xnameSummary)); var description = metadataCache.GetString(GetString(properties, _xnameDescription)); var iconUrl = metadataCache.GetString(GetString(properties, _xnameIconUrl)); var licenseUrl = metadataCache.GetString(GetString(properties, _xnameLicenseUrl)); var projectUrl = metadataCache.GetString(GetString(properties, _xnameProjectUrl)); var reportAbuseUrl = metadataCache.GetString(GetString(properties, _xnameReportAbuseUrl)); var tags = metadataCache.GetString(GetString(properties, _xnameTags)); var dependencies = metadataCache.GetString(GetString(properties, _xnameDependencies)); var downloadCount = metadataCache.GetString(GetString(properties, _xnameDownloadCount)); var requireLicenseAcceptance = StringComparer.OrdinalIgnoreCase.Equals(bool.TrueString, GetString(properties, _xnameRequireLicenseAcceptance)); var packageHash = metadataCache.GetString(GetString(properties, _xnamePackageHash)); var packageHashAlgorithm = metadataCache.GetString(GetString(properties, _xnamePackageHashAlgorithm)); NuGetVersion minClientVersion = null; var minClientVersionString = GetString(properties, _xnameMinClientVersion); if (!string.IsNullOrEmpty(minClientVersionString)) { if (NuGetVersion.TryParse(minClientVersionString, out minClientVersion)) { minClientVersion = metadataCache.GetVersion(minClientVersionString); } } var created = GetDate(properties, _xnameCreated); var lastEdited = GetDate(properties, _xnameLastEdited); var published = GetDate(properties, _xnamePublished); IEnumerable <string> owners = null; IEnumerable <string> authors = null; var authorNode = element.Element(_xnameAuthor); if (authorNode != null) { authors = authorNode.Elements(_xnameName).Select(e => metadataCache.GetString(e.Value)); } return(new V2FeedPackageInfo(new PackageIdentity(identityId, version), title, summary, description, authors, owners, iconUrl, licenseUrl, projectUrl, reportAbuseUrl, tags, created, lastEdited, published, dependencies, requireLicenseAcceptance, downloadUrl, downloadCount, packageHash, packageHashAlgorithm, minClientVersion)); }
public static bool IsSemVer200(this NuGetVersion self) { return(self.ReleaseLabels.Count() > 1 || self.HasMetadata); }
public void ParseReadsSemverAndHybridSemverVersionNumbers(string versionString, string expectedString, string releaseString) { // Arrange var expected = new NuGetVersion(new Version(expectedString), releaseString); // Act var actual = NuGetVersion.Parse(versionString); // Assert Assert.Equal(expected.Version, actual.Version); Assert.Equal(expected.Release, actual.Release); }
public NuGetArtifactTester(string file) { _reader = new PackageArchiveReader(ZipFile.Open(file, ZipArchiveMode.Read)); Identity = _reader.NuspecReader.GetIdentity(); PackageVersion = _reader.NuspecReader.GetVersion(); }
public void ToStringConstructedFromVersionAndSpecialVersionConstructor(string versionString, string specialVersion, string expected) { // Arrange var version = new Version(versionString); // Act var semVer = new NuGetVersion(version, specialVersion); // Assert Assert.Equal(expected, semVer.ToString()); }
private string GetPackageFilePath(string id, NuGetVersion version) { return Path.Combine(Source, id + "." + version.ToNormalizedString() + Constants.PackageExtension); }
public static VersionRange ReplaceMaxVersion(this VersionRange range, NuGetVersion newMaxVersion) { return(new VersionRange(range.MinVersion, range.IsMinInclusive, newMaxVersion, range.IsMaxInclusive, range.Float, range.OriginalString)); }
public async Task PackageExpander_Recovers_WhenFileIsLocked() { // Arrange using (var package = TestPackages.GetNearestReferenceFilteringPackage()) { var version = new NuGetVersion(package.Version); var identity = new PackageIdentity(package.Id, version); var packagesDir = TestDirectory.Create(); var pathResolver = new VersionFolderPathResolver(packagesDir); var token = CancellationToken.None; var logger = NullLogger.Instance; var versionFolderPathContext = new VersionFolderPathContext( identity, packagesDir, logger, packageSaveMode: PackageSaveMode.Defaultv3, xmlDocFileSaveMode: XmlDocFileSaveMode.None); var packageDir = pathResolver.GetInstallPath(package.Id, identity.Version); Assert.False(Directory.Exists(packageDir), packageDir + " exist"); string filePathToLock = Path.Combine(packageDir, "lib", "net40", "two.dll"); // Act using (var stream = package.File.OpenRead()) { var cts = new CancellationTokenSource(DefaultTimeOut); Func <CancellationToken, Task <bool> > action = (ct) => { Assert.ThrowsAnyAsync <IOException>(async() => await PackageExtractor.InstallFromSourceAsync( str => stream.CopyToAsync(stream, bufferSize: 8192, cancellationToken: token), versionFolderPathContext, token)); return(Task.FromResult(true)); }; await ConcurrencyUtilities.ExecuteWithFileLockedAsync(filePathToLock, action, cts.Token); } AssertDirectoryExists(packageDir, packageDir + " does not exist"); Assert.NotEmpty(Directory.EnumerateFiles(packageDir)); using (var stream = package.File.OpenRead()) { await PackageExtractor.InstallFromSourceAsync(async (d) => await stream.CopyToAsync(d), versionFolderPathContext, token); } // Assert var filePath = pathResolver.GetPackageFilePath(package.Id, identity.Version); Assert.True(File.Exists(filePath), filePath + " does not exist"); var dllPath = Path.Combine(packageDir, "lib", "net40", "one.dll"); Assert.True(File.Exists(dllPath), dllPath + " does not exist"); Assert.True(File.Exists(filePathToLock)); // Make sure the actual file from the zip was extracted Assert.Equal(new byte[] { 0 }, File.ReadAllBytes(filePathToLock)); } }