Пример #1
0
        public async Task StandaloneProject_BasicRestore()
        {
            // Arrange
            using (var pathContext = new SimpleTestPathContext())
            {
                var logger = new TestLogger();
                var dgFile = new DependencyGraphSpec();

                var projectJson = @"
                {
                  ""frameworks"": {
                    ""netstandard1.6"": {
                      ""dependencies"": {
                        ""a"": ""1.0.0""
                      }
                    }
                  }
                }";

                var spec = JsonPackageSpecReader.GetPackageSpec(projectJson, "x", Path.Combine(pathContext.SolutionRoot, "project.json"));
                spec.RestoreMetadata = new ProjectRestoreMetadata();
                spec.RestoreMetadata.ProjectStyle      = ProjectStyle.Standalone;
                spec.RestoreMetadata.OutputPath        = Path.Combine(pathContext.SolutionRoot, "x");
                spec.RestoreMetadata.ProjectUniqueName = "x";
                spec.RestoreMetadata.ProjectName       = "x";
                spec.RestoreMetadata.ProjectPath       = Path.Combine(pathContext.SolutionRoot, "x.csproj");

                dgFile.AddProject(spec);
                dgFile.AddRestore("x");

                await SimpleTestPackageUtility.CreateFolderFeedV3(pathContext.PackageSource, new PackageIdentity("a", NuGetVersion.Parse("1.0.0")));

                // Act
                var result = await CommandsTestUtility.RunSingleRestore(dgFile, pathContext, logger);

                var path = Path.Combine(spec.RestoreMetadata.OutputPath, "project.assets.json");

                // Assert
                Assert.True(result.Success, "Failed: " + string.Join(Environment.NewLine, logger.Messages));
                Assert.True(File.Exists(path));

                var lockFormat = new LockFileFormat();
                var lockFile   = lockFormat.Read(path);

                Assert.Equal(NuGetFramework.Parse("netstandard1.6"), lockFile.Targets.Single().TargetFramework);
                Assert.Equal("a", lockFile.Targets.Single().Libraries.Single().Name);
            }
        }
Пример #2
0
        public void PackagesLockFile_Equals()
        {
            Func <PackagesLockFile> getLockFile = () =>
            {
                var lockFile = new PackagesLockFile()
                {
                    Version = 1,

                    Targets = new List <PackagesLockFileTarget>()
                    {
                        new PackagesLockFileTarget()
                        {
                            TargetFramework = FrameworkConstants.CommonFrameworks.Net45,

                            Dependencies = new List <LockFileDependency>()
                            {
                                new LockFileDependency()
                                {
                                    Id               = "PackageA",
                                    Type             = PackageDependencyType.Direct,
                                    RequestedVersion = VersionRange.Parse("1.0.0"),
                                    ResolvedVersion  = NuGetVersion.Parse("1.0.0"),
                                    ContentHash      = "sha1",
                                    Dependencies     = new List <PackageDependency>()
                                    {
                                        new PackageDependency("PackageB", VersionRange.Parse("1.0.0"))
                                    }
                                },
                                new LockFileDependency()
                                {
                                    Id              = "PackageB",
                                    Type            = PackageDependencyType.Transitive,
                                    ResolvedVersion = NuGetVersion.Parse("1.0.0"),
                                    ContentHash     = "sha2"
                                }
                            }
                        },
                        new PackagesLockFileTarget()
                        {
                            TargetFramework = FrameworkConstants.CommonFrameworks.Net45,

                            RuntimeIdentifier = "win10-arm",

                            Dependencies = new List <LockFileDependency>()
                            {
                                new LockFileDependency()
                                {
                                    Id               = "PackageA",
                                    Type             = PackageDependencyType.Direct,
                                    RequestedVersion = VersionRange.Parse("1.0.0"),
                                    ResolvedVersion  = NuGetVersion.Parse("1.0.0"),
                                    ContentHash      = "sha3",
                                    Dependencies     = new List <PackageDependency>()
                                    {
                                        new PackageDependency("runtime.win10-arm.PackageA", VersionRange.Parse("1.0.0"))
                                    }
                                },
                                new LockFileDependency()
                                {
                                    Id              = "runtime.win10-arm.PackageA",
                                    Type            = PackageDependencyType.Transitive,
                                    ResolvedVersion = NuGetVersion.Parse("1.0.0"),
                                    ContentHash     = "sha4"
                                }
                            }
                        }
                    }
                };

                return(lockFile);
            };

            var self  = getLockFile();
            var other = getLockFile();

            Assert.NotSame(self, other);
            Assert.Equal(self, other);
        }
Пример #3
0
 protected NuGetVersion Parse(string input)
 {
     return(NuGetVersion.Parse(input));
 }
 /// <summary>
 /// Creates the version range
 /// </summary>
 /// <param name="minVersion">The minimum required version</param>
 /// <returns>The version range</returns>
 internal static VersionRange CreateVersionRange(string minVersion)
 {
     return(new VersionRange(NuGetVersion.Parse(minVersion)));
 }
        public async Task CreatePathContextAsync_FromAssetsFile()
        {
            // Arrange
            using (var testDirectory = TestDirectory.Create())
            {
                var userPackageFolder = Path.Combine(testDirectory.Path, "packagesA");
                Directory.CreateDirectory(userPackageFolder);

                var fallbackPackageFolder = Path.Combine(testDirectory.Path, "packagesB");
                Directory.CreateDirectory(fallbackPackageFolder);

                await SimpleTestPackageUtility.CreateFolderFeedV3Async(
                    userPackageFolder,
                    new PackageIdentity("Foo", NuGetVersion.Parse("1.0.1")));

                await SimpleTestPackageUtility.CreateFolderFeedV3Async(
                    fallbackPackageFolder,
                    new PackageIdentity("Bar", NuGetVersion.Parse("1.0.2")));

                var target = new VsPathContextProvider(
                    Mock.Of <ISettings>(),
                    Mock.Of <IVsSolutionManager>(),
                    Mock.Of <ILogger>(),
                    getLockFileOrNullAsync: _ =>
                {
                    var lockFile = new LockFile
                    {
                        PackageFolders = new[]
                        {
                            new LockFileItem(userPackageFolder),
                            new LockFileItem(fallbackPackageFolder)
                        },
                        Libraries = new[]
                        {
                            new LockFileLibrary
                            {
                                Type    = LibraryType.Package,
                                Name    = "Foo",
                                Version = NuGetVersion.Parse("1.0.1")
                            },
                            new LockFileLibrary
                            {
                                Type    = LibraryType.Package,
                                Name    = "Bar",
                                Version = NuGetVersion.Parse("1.0.2")
                            }
                        }
                    };

                    return(Task.FromResult(lockFile));
                });

                var project = Mock.Of <BuildIntegratedNuGetProject>();

                // Act
                var actual = await target.CreatePathContextAsync(project, CancellationToken.None);

                // Assert
                Assert.NotNull(actual);
                Assert.Equal(userPackageFolder, actual.UserPackageFolder);
                Assert.Equal(
                    new[] { fallbackPackageFolder },
                    actual.FallbackPackageFolders.Cast <string>().ToArray());

                string actualPackageDirectory = null;

                var packageRootA = Path.Combine(userPackageFolder, "Foo", "1.0.1");
                var assetFileA   = Path.Combine(packageRootA, "lib", "net40", "a.dll");
                Assert.True(actual.TryResolvePackageAsset(assetFileA, out actualPackageDirectory));
                Assert.Equal(packageRootA, actualPackageDirectory, ignoreCase: true);

                var packageRootB = Path.Combine(fallbackPackageFolder, "Bar", "1.0.2");
                var assetFileB   = Path.Combine(packageRootB, "lib", "net46", "b.dll");
                Assert.True(actual.TryResolvePackageAsset(assetFileB, out actualPackageDirectory));
                Assert.Equal(packageRootB, actualPackageDirectory, ignoreCase: true);
            }
        }
        public void DependencyGraphSpec_RoundTripMSBuildMetadata()
        {
            // Arrange
            var frameworks = new List <TargetFrameworkInformation>();

            frameworks.Add(new TargetFrameworkInformation()
            {
                FrameworkName = NuGetFramework.Parse("net45")
            });

            var spec = new PackageSpec(frameworks);

            spec.Version = NuGetVersion.Parse("24.5.1.2-alpha.1.2+a.b.c");
            var msbuildMetadata = new ProjectRestoreMetadata();

            spec.RestoreMetadata = msbuildMetadata;

            msbuildMetadata.ProjectUniqueName = "A55205E7-4D08-4672-8011-0925467CC45F";
            msbuildMetadata.ProjectPath       = "c:\\x\\x.csproj";
            msbuildMetadata.ProjectName       = PackageSpecName;
            msbuildMetadata.ProjectJsonPath   = "c:\\x\\project.json";
            msbuildMetadata.ProjectStyle      = ProjectStyle.PackageReference;
            msbuildMetadata.PackagesPath      = "c:\\packages";
            msbuildMetadata.Sources           = new[] { new PackageSource("https://api.nuget.org/v3/index.json") };

            var tfmGroup = new ProjectRestoreMetadataFrameworkInfo(NuGetFramework.Parse("net45"));

            msbuildMetadata.TargetFrameworks.Add(tfmGroup);

            tfmGroup.ProjectReferences.Add(new ProjectRestoreReference()
            {
                ProjectUniqueName = "44B29B8D-8413-42D2-8DF4-72225659619B",
                ProjectPath       = "c:\\a\\a.csproj"
            });

            tfmGroup.ProjectReferences.Add(new ProjectRestoreReference()
            {
                ProjectUniqueName = "78A6AD3F-9FA5-47F6-A54E-84B46A48CB2F",
                ProjectPath       = "c:\\b\\b.csproj"
            });

            msbuildMetadata.FallbackFolders.Add("c:\\fallback1");
            msbuildMetadata.FallbackFolders.Add("c:\\fallback2");


            msbuildMetadata.ConfigFilePaths.Add("c:\\nuget.config");
            msbuildMetadata.ConfigFilePaths.Add("d:\\nuget.config");

            msbuildMetadata.CrossTargeting          = true;
            msbuildMetadata.LegacyPackagesDirectory = true;

            // Act
            PackageSpec            readSpec         = PackageSpecTestUtility.RoundTrip(spec, PackageSpecName, PackageSpecPath);
            ProjectRestoreMetadata msbuildMetadata2 = readSpec.RestoreMetadata;

            // Assert
            Assert.NotNull(msbuildMetadata2);
            Assert.Equal("A55205E7-4D08-4672-8011-0925467CC45F", msbuildMetadata2.ProjectUniqueName);
            Assert.Equal("c:\\x\\x.csproj", msbuildMetadata2.ProjectPath);
            Assert.Equal(PackageSpecName, msbuildMetadata2.ProjectName);
            Assert.Equal("c:\\x\\project.json", msbuildMetadata2.ProjectJsonPath);
            Assert.Equal(ProjectStyle.PackageReference, msbuildMetadata2.ProjectStyle);
            Assert.Equal("c:\\packages", msbuildMetadata2.PackagesPath);
            Assert.Equal("https://api.nuget.org/v3/index.json", string.Join("|", msbuildMetadata.Sources.Select(s => s.Source)));
            Assert.Equal("c:\\fallback1|c:\\fallback2", string.Join("|", msbuildMetadata2.FallbackFolders));
            Assert.Equal("c:\\nuget.config|d:\\nuget.config", string.Join("|", msbuildMetadata.ConfigFilePaths));
            Assert.Equal("44B29B8D-8413-42D2-8DF4-72225659619B|c:\\a\\a.csproj|78A6AD3F-9FA5-47F6-A54E-84B46A48CB2F|c:\\b\\b.csproj", string.Join("|", msbuildMetadata2.TargetFrameworks.Single().ProjectReferences.Select(e => $"{e.ProjectUniqueName}|{e.ProjectPath}")));
            Assert.True(msbuildMetadata.CrossTargeting);
            Assert.True(msbuildMetadata.LegacyPackagesDirectory);

            // Verify build metadata is not lost.
            Assert.Equal("24.5.1.2-alpha.1.2+a.b.c", readSpec.Version.ToFullString());
        }
Пример #7
0
        public override Task <IEnumerable <UIPackageMetadata> > GetMetadata(IEnumerable <PackageIdentity> packages, CancellationToken token)
        {
            var results = new List <UIPackageMetadata>();

            foreach (var group in packages.GroupBy(e => e.Id, StringComparer.OrdinalIgnoreCase))
            {
                if (group.Count() == 1)
                {
                    // optimization for a single package
                    var package = group.Single();

                    var result = V2Client.FindPackage(package.Id, SemanticVersion.Parse(package.Version.ToString()));

                    if (result != null)
                    {
                        results.Add(GetVisualStudioUIPackageMetadata(result));
                    }
                }
                else
                {
                    // batch mode
                    var foundPackages = V2Client.FindPackagesById(group.Key)
                                        .Where(p => group.Any(e => VersionComparer.VersionRelease.Equals(e.Version, NuGetVersion.Parse(p.Version.ToString()))))
                                        .Select(p => GetVisualStudioUIPackageMetadata(p));

                    results.AddRange(foundPackages);
                }
            }

            return(Task.FromResult <IEnumerable <UIPackageMetadata> >(results));
        }
Пример #8
0
 static RemotePackageArchiveDownloaderTests()
 {
     _packageIdentity = new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0"));
 }
Пример #9
0
        public async Task GetPackageContentWhenExists(string index)
        {
            packageRepo.Setup(r => r.FindOrNullAsync(It.IsAny <PackageIdentity>(), It.IsAny <bool>(), It.IsAny <bool>()))
            .ReturnsAsync(dummy1_0_0).Verifiable();
            packageRepo.Setup(r => r.IncrementDownloadCountAsync(It.IsAny <PackageIdentity>()))
            .ReturnsAsync(true);
            storageRepo.Setup(r => r.GetPackageStreamAsync(It.IsAny <PackageIdentity>()))
            .ReturnsAsync(new MemoryStream(new byte[3] {
                1, 2, 3
            }));
            using (TestServer server = serverBuilder.Build())
            {
                var httpClient = server.CreateClient();
                var result     = await httpClient.GetAsync(index + "/contents/dummy/1.0.0");

                Assert.Equal(HttpStatusCode.OK, result.StatusCode);
                Assert.Equal("application/zip", result.Content.Headers.ContentType.MediaType);
                storageRepo.Verify(r => r.GetPackageStreamAsync(It.Is <PackageIdentity>(p =>
                                                                                        p.Version.Equals(NuGetVersion.Parse("1.0.0")) &&
                                                                                        p.Id == "dummy")), Times.Exactly(1));
                var bytes = await result.Content.ReadAsByteArrayAsync();

                Assert.Equal(new byte[] { 1, 2, 3 }, bytes);
            }
        }
Пример #10
0
        /// <summary>
        /// <para> Return false if the installation arguments are different. Otherwise,</para>
        /// <para> Return true if any of below cases is satisfied:</para>
        /// <para>      1) Package with same version and from same feed already exist in local repo</para>
        /// <para>      2) If given feedUrl is null</para>
        /// <para>              Try to use feed from local package, if feed from local package also null, fallback to default feed</para>
        /// <para>              Check if version from query is same as local package</para>
        /// <para>      3) If given version and feedUrl are null</para>
        /// <para>              Try to use feed from local package, if feed from local package also null, fallback to default feed</para>
        /// <para>              Check if version from query is same as local package</para>
        /// </summary>
        private async Task <bool> IsSiteExtensionInstalled(string id, string version, string feedUrl, string installationArgs)
        {
            ITracer      tracer = _traceFactory.GetTracer();
            JsonSettings siteExtensionSettings        = GetSettingManager(id);
            string       localPackageVersion          = siteExtensionSettings.GetValue(_versionSetting);
            string       localPackageFeedUrl          = siteExtensionSettings.GetValue(_feedUrlSetting);
            string       localPackageInstallationArgs = siteExtensionSettings.GetValue(_installationArgs);
            NuGetVersion localPkgVer  = null;
            NuGetVersion lastFoundVer = null;
            bool         isInstalled  = false;

            // Shortcircuit check: if the installation arguments do not match, then we should return false here to avoid other checks which are now unnecessary.
            if (!string.Equals(localPackageInstallationArgs, installationArgs))
            {
                return(false);
            }

            if (!string.IsNullOrEmpty(localPackageVersion))
            {
                localPkgVer = NuGetVersion.Parse(localPackageVersion);
            }

            // Try to use given feed
            // If given feed is null, try with feed that from local package
            // And GetRemoteRepositories will fallback to use default feed if pass in feed param is null
            IEnumerable <SourceRepository> remoteRepos = GetRemoteRepositories(feedUrl ?? localPackageFeedUrl);

            foreach (SourceRepository rr in remoteRepos)
            {
                // case 1 and 2
                if (!string.IsNullOrWhiteSpace(version) &&
                    version.Equals(localPackageVersion, StringComparison.OrdinalIgnoreCase) &&
                    rr.PackageSource.Source.Equals(localPackageFeedUrl, StringComparison.OrdinalIgnoreCase))
                {
                    isInstalled = true;
                }
                else if (string.IsNullOrWhiteSpace(version) &&
                         string.IsNullOrWhiteSpace(feedUrl) &&
                         string.Equals(localPackageInstallationArgs, installationArgs))
                {
                    // case 3
                    UIPackageMetadata remotePackage = await rr.GetLatestPackageByIdFromSrcRepo(id);

                    if (remotePackage != null)
                    {
                        tracer.Trace("Found version: {0} on feed: {1}",
                                     remotePackage.Identity.Version.ToNormalizedString(),
                                     rr.PackageSource.Source);
                        if (lastFoundVer == null || lastFoundVer < remotePackage.Identity.Version)
                        {
                            lastFoundVer = remotePackage.Identity.Version;
                        }
                    }
                }
            }

            if (lastFoundVer != null && localPkgVer != null && lastFoundVer <= localPkgVer)
            {
                isInstalled = true;
            }

            return(isInstalled);
        }
Пример #11
0
        public async Task GetPackagesSpecifiedIdAndVersionWhenExists(string index)
        {
            packageRepo.Setup(r => r.FindOrNullAsync(It.IsAny <PackageIdentity>(), It.IsAny <bool>(), It.IsAny <bool>()))
            .ReturnsAsync(dummy1_0_0).Verifiable();
            using (TestServer server = serverBuilder.Build())
            {
                var httpClient = server.CreateClient();
                var result     = await httpClient.GetAsync(index + "/Packages(Id='dummy',Version='1.0.0')");

                Assert.Equal(HttpStatusCode.OK, result.StatusCode);
                Assert.Equal("application/atom+xml", result.Content.Headers.ContentType.MediaType);
                packageRepo.Verify(r => r.FindOrNullAsync(new PackageIdentity("dummy", NuGetVersion.Parse("1.0.0")), false, true), Times.Exactly(1));
                var responseText = await result.Content.ReadAsStringAsync();

                var entries    = XmlFeedHelper.ParsePage(XDocument.Parse(responseText));
                var dummyEntry = Assert.Single(entries);
                AssertDummyEntry(dummyEntry);
            }
        }
Пример #12
0
        public async Task GetPackagesSpecifiedIdAndVersionEmptyRepository(string index)
        {
            packageRepo.Setup(r => r.FindOrNullAsync(It.IsAny <PackageIdentity>(), It.IsAny <bool>(), It.IsAny <bool>()))
            .ReturnsAsync(null as Package).Verifiable();
            using (TestServer server = serverBuilder.Build())
            {
                var httpClient = server.CreateClient();
                var result     = await httpClient.GetAsync(index + "/Packages(Id='dummy',Version='1.0.0')");

                Assert.Equal(HttpStatusCode.NotFound, result.StatusCode);
                packageRepo.Verify(r => r.FindOrNullAsync(new PackageIdentity("dummy", NuGetVersion.Parse("1.0.0")), false, true), Times.Exactly(1));
            }
        }
Пример #13
0
        IEnumerable <ExternalDependency> GetKestrelLibuvDependencies(FilePath path)
        {
            var packageDirectoryPath = path.ParentDirectory.ParentDirectory.ParentDirectory;

            // Get all the available libuv's
            var allPackagesPath   = packageDirectoryPath.ParentDirectory.ParentDirectory;
            var libuvPackagesPath = allPackagesPath.Combine("libuv");
            var libuvVersions     = libuvPackagesPath.EnumerateDirectories()
                                    .Select(dir => NuGetVersion.Parse(dir.Name))
                                    .ToArray();

            // Read the transport's nuspec to find the best matching version of libuv
            var nuspecPath = packageDirectoryPath.Combine(
                "microsoft.aspnetcore.server.kestrel.transport.libuv.nuspec");
            var nuspecData             = new NuspecReader(nuspecPath);
            var libuvDependencyVersion = nuspecData.GetDependencyGroups()
                                         .SelectMany(dg => dg.Packages)
                                         .Where(p => PackageIdComparer.Equals(p.Id, "Libuv"))
                                         .Distinct(PackageIdComparer.Default)
                                         .SingleOrDefault()
                                         ?.VersionRange
                                         .FindBestMatch(libuvVersions);

            var libuvPackagePath = libuvPackagesPath.Combine(libuvDependencyVersion.ToString());

            var architecture = agentArchitecture.ToString().ToLowerInvariant();
            var isMac        = false;

            switch (HostEnvironment.OS)
            {
            case HostOS.Windows:
                break;

            case HostOS.macOS:
                isMac = true;
                break;

            default:
                yield break;
            }

            string runtimeName, nativeLibName;

            switch (AgentType)
            {
            case AgentType.WPF:
                // We need the win7-<bitness> library here.
                nativeLibName = "libuv.dll";
                runtimeName   = $"win-{architecture}";
                break;

            case AgentType.Console:
            case AgentType.MacNet45:
            case AgentType.MacMobile:
            case AgentType.DotNetCore:
                nativeLibName = isMac ? "libuv.dylib" : "libuv.dll";
                runtimeName   = isMac ? "osx" : $"win-{architecture}";
                break;

            default:
                yield break;
            }

            var nativeLibraryPath = libuvPackagePath.Combine(
                "runtimes",
                runtimeName,
                "native",
                nativeLibName
                );

            if (nativeLibraryPath.FileExists)
            {
                yield return(new NativeDependency(nativeLibraryPath.Name, nativeLibraryPath));
            }
        }
        public async Task <SearchResponse> SearchAsync(
            SearchRequest request,
            CancellationToken cancellationToken)
        {
            var searchText = BuildSeachQuery(request.Query, request.PackageType, request.Framework);
            var filter     = BuildSearchFilter(request.IncludePrerelease, request.IncludeSemVer2);
            var parameters = new SearchParameters
            {
                IncludeTotalResultCount = true,
                QueryType = QueryType.Full,
                Skip      = request.Skip,
                Top       = request.Take,
                Filter    = filter
            };

            var response = await _searchClient.Documents.SearchAsync <PackageDocument>(
                searchText,
                parameters,
                cancellationToken : cancellationToken);

            var results = new List <SearchResult>();

            foreach (var result in response.Results)
            {
                var document = result.Document;
                var versions = new List <SearchResultVersion>();

                if (document.Versions.Length != document.VersionDownloads.Length)
                {
                    throw new InvalidOperationException($"Invalid document {document.Key} with mismatched versions");
                }

                for (var i = 0; i < document.Versions.Length; i++)
                {
                    var version = NuGetVersion.Parse(document.Versions[i]);

                    versions.Add(new SearchResultVersion
                    {
                        RegistrationLeafUrl = _url.GetRegistrationLeafUrl(document.Id, version),
                        Version             = document.Versions[i],
                        Downloads           = long.Parse(document.VersionDownloads[i]),
                    });
                }

                var iconUrl = document.HasEmbeddedIcon
                    ? _url.GetPackageIconDownloadUrl(document.Id, NuGetVersion.Parse(document.Version))
                    : document.IconUrl;

                results.Add(new SearchResult
                {
                    PackageId            = document.Id,
                    Version              = document.Version,
                    Description          = document.Description,
                    Authors              = document.Authors,
                    IconUrl              = iconUrl,
                    LicenseUrl           = document.LicenseUrl,
                    ProjectUrl           = document.ProjectUrl,
                    RegistrationIndexUrl = _url.GetRegistrationIndexUrl(document.Id),
                    Summary              = document.Summary,
                    Tags           = document.Tags,
                    Title          = document.Title,
                    TotalDownloads = document.TotalDownloads,
                    Versions       = versions
                });
            }

            return(new SearchResponse
            {
                TotalHits = response.Count.Value,
                Data = results,
                Context = SearchContext.Default(_url.GetPackageMetadataResourceUrl())
            });
        }
Пример #15
0
 public PackageInfoCollection(string version)
 {
     _version = NuGetVersion.Parse(version);
 }