public void TableRestoreTest() { var restoreCommand = new RestoreCommand(); var options = new TableCommandOptions { Mode = "restore", Source = DataLocation, Destination = DevelopmentStorage }; restoreCommand.Run(options); }
public static void Register(CommandLineApplication cmdApp, ReportsFactory reportsFactory, IApplicationEnvironment appEnvironment) { cmdApp.Command("install", c => { c.Description = "Install the given dependency"; var argName = c.Argument("[name]", "Name of the dependency to add"); var argVersion = c.Argument("[version]", "Version of the dependency to add, default is the latest version."); var argProject = c.Argument("[project]", "Path to project, default is current directory"); var feedCommandLineOptions = FeedCommandLineOptions.Add(c); c.HelpOption("-?|-h|--help"); c.OnExecute(async () => { c.ShowRootCommandFullNameAndVersion(); var feedOptions = feedCommandLineOptions.GetOptions(); var reports = reportsFactory.CreateReports(feedOptions.Quiet); var addCmd = new AddCommand(); addCmd.Reports = reports; addCmd.Name = argName.Value; addCmd.Version = argVersion.Value; addCmd.ProjectDir = argProject.Value; var restoreCmd = new RestoreCommand(appEnvironment); restoreCmd.Reports = reports; restoreCmd.FeedOptions = feedOptions; restoreCmd.RestoreDirectories.Add(argProject.Value); if (!string.IsNullOrEmpty(feedOptions.Proxy)) { Environment.SetEnvironmentVariable("http_proxy", feedOptions.Proxy); } var installCmd = new InstallCommand(addCmd, restoreCmd); installCmd.Reports = reports; var success = await installCmd.ExecuteCommand(); return success ? 0 : 1; }); }); }
public static void Register(CommandLineApplication cmdApp, ReportsFactory reportsFactory, IApplicationEnvironment applicationEnvironment, IRuntimeEnvironment runtimeEnvironment) { cmdApp.Command("restore", c => { c.Description = "Restore packages"; var argRoot = c.Argument("[root]", "List of projects and project folders to restore. Each value can be: a path to a project.json or global.json file, or a folder to recursively search for project.json files.", multipleValues: true); var feedCommandLineOptions = FeedCommandLineOptions.Add(c); var optLock = c.Option("--lock", "Creates dependencies file with locked property set to true. Overwrites file if it exists.", CommandOptionType.NoValue); var optUnlock = c.Option("--unlock", "Creates dependencies file with locked property set to false. Overwrites file if it exists.", CommandOptionType.NoValue); var optRuntimes = c.Option("--runtime <RID>", "List of runtime identifiers to restore for", CommandOptionType.MultipleValue); c.HelpOption("-?|-h|--help"); c.OnExecute(async () => { c.ShowRootCommandFullNameAndVersion(); var feedOptions = feedCommandLineOptions.GetOptions(); var command = new RestoreCommand(applicationEnvironment); command.Reports = reportsFactory.CreateReports(feedOptions.Quiet); command.RestoreDirectories.AddRange(argRoot.Values); command.FeedOptions = feedOptions; command.Lock = optLock.HasValue(); command.Unlock = optUnlock.HasValue(); command.RequestedRuntimes = optRuntimes.Values; command.FallbackRuntimes = runtimeEnvironment.GetDefaultRestoreRuntimes(); if (!string.IsNullOrEmpty(feedOptions.Proxy)) { Environment.SetEnvironmentVariable("http_proxy", feedOptions.Proxy); } var success = await command.Execute(); return success ? 0 : 1; }); }); }
public async Task UWPRestore_BlankUWPAppV1() { // Arrange var sources = new List <PackageSource>(); sources.Add(new PackageSource("https://api.nuget.org/v3/index.json")); using (var packagesDir = TestDirectory.Create()) using (var projectDir = TestDirectory.Create()) { var configJson = JObject.Parse(@"{ ""dependencies"": { ""Microsoft.NETCore.UniversalWindowsPlatform"": ""5.0.0"" }, ""frameworks"": { ""uap10.0"": {} }, ""runtimes"": { ""win10-arm"": {}, ""win10-arm-aot"": {}, ""win10-x86"": {}, ""win10-x86-aot"": {}, ""win10-x64"": {}, ""win10-x64-aot"": {} } }"); var specPath = Path.Combine(projectDir, "TestProject", "project.json"); var spec = JsonPackageSpecReader.GetPackageSpec(configJson.ToString(), "TestProject", specPath); var logger = new TestLogger(); var request = new TestRestoreRequest(spec, sources, packagesDir, logger); request.LockFilePath = Path.Combine(projectDir, "project.lock.json"); // Set the lock file version to v1 to force a downgrade request.LockFileVersion = 1; var lockFileFormat = new LockFileFormat(); var command = new RestoreCommand(request); var expectedStream = GetResource("NuGet.Commands.FuncTest.compiler.resources.uwpBlankAppV1.json"); JObject expectedJson = null; using (var reader = new StreamReader(expectedStream)) { expectedJson = JObject.Parse(reader.ReadToEnd()); } // Act var result = await command.ExecuteAsync(); await result.CommitAsync(logger, CancellationToken.None); var lockFileJson = JObject.Parse(File.OpenText(request.LockFilePath).ReadToEnd()); RemovePackageFolders(lockFileJson); // Assert Assert.True(result.Success); Assert.Equal(0, result.CompatibilityCheckResults.Sum(checkResult => checkResult.Issues.Count)); Assert.Equal(0, logger.Errors); Assert.Equal(0, logger.Warnings); Assert.Equal(118, result.GetAllInstalled().Count); Assert.Equal(expectedJson.ToString(), lockFileJson.ToString()); } }
public async Task CompatilibityChecker_PackageCompatibility_VerifyAvailableFrameworksIgnoresInvalidAssetsAsync() { // Arrange var sources = new List <PackageSource>(); var project1Json = @" { ""version"": ""1.0.0"", ""description"": """", ""authors"": [ ""author"" ], ""tags"": [ """" ], ""projectUrl"": """", ""licenseUrl"": """", ""frameworks"": { ""netstandard1.0"": { ""dependencies"": { ""packageA"": { ""version"": ""1.0.0"" } } } } }"; using (var workingDir = TestDirectory.Create()) { var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages")); var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource")); var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1")); packagesDir.Create(); packageSource.Create(); project1.Create(); sources.Add(new PackageSource(packageSource.FullName)); File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json); var specPath1 = Path.Combine(project1.FullName, "project.json"); var spec1 = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1); var logger = new TestLogger(); var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger) { LockFilePath = Path.Combine(project1.FullName, "project.lock.json") }; var packageA = new SimpleTestPackageContext("packageA"); packageA.AddFile("lib/netstandard1.1/valid.dll"); packageA.AddFile("lib/netstandard1.0/x86/invalid.dll"); await SimpleTestPackageUtility.CreatePackagesAsync(packageSource.FullName, packageA); // Act var command = new RestoreCommand(request); var result = await command.ExecuteAsync(); await result.CommitAsync(logger, CancellationToken.None); // Assert Assert.False(result.Success, logger.ShowErrors()); // Verify both libraries were installed Assert.Equal(1, result.LockFile.Libraries.Count); var issue = result.CompatibilityCheckResults.SelectMany(check => check.Issues).Single(); Assert.Equal("Package packageA 1.0.0 is not compatible with netstandard1.0 (.NETStandard,Version=v1.0). Package packageA 1.0.0 supports: netstandard1.1 (.NETStandard,Version=v1.1)", issue.Format()); } }
public async Task FallbackFolderRestore_NoPackagesFoundInFallbackAsync() { // Arrange var sources = new List <PackageSource>(); var project1Json = @" { ""version"": ""1.0.0"", ""description"": """", ""authors"": [ ""author"" ], ""tags"": [ """" ], ""projectUrl"": """", ""licenseUrl"": """", ""frameworks"": { ""netstandard1.3"": { ""dependencies"": { ""packageA"": ""1.0.0"", ""packageB"": ""1.0.0"" } } } }"; using (var workingDir = TestDirectory.Create()) { var fallbackFolder = new DirectoryInfo(Path.Combine(workingDir, "fallbackFolder")); var fallbackFolder2 = new DirectoryInfo(Path.Combine(workingDir, "fallbackFolder2")); var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages")); var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource")); var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1")); packageSource.Create(); project1.Create(); fallbackFolder.Create(); fallbackFolder2.Create(); sources.Add(new PackageSource(packageSource.FullName)); File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json); var specPath1 = Path.Combine(project1.FullName, "project.json"); var spec1 = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1).EnsureProjectJsonRestoreMetadata(); var logger = new TestLogger(); var request = new TestRestoreRequest( spec1, sources, packagesDir.FullName, new List <string>() { fallbackFolder.FullName, fallbackFolder2.FullName }, logger) { LockFilePath = Path.Combine(project1.FullName, "project.lock.json") }; var packageBContext = new SimpleTestPackageContext() { Id = "packageB", Version = "1.0.0" }; var packageAContext = new SimpleTestPackageContext() { Id = "packageA", Version = "1.0.0" }; await SimpleTestPackageUtility.CreatePackagesAsync( packageSource.FullName, packageAContext, packageBContext); // Act var command = new RestoreCommand(request); var result = await command.ExecuteAsync(); var lockFile = result.LockFile; await result.CommitAsync(logger, CancellationToken.None); // Assert Assert.True(result.Success); Assert.Equal(2, lockFile.Libraries.Count); Assert.Equal(2, result.GetAllInstalled().Count); Assert.Equal(2, Directory.GetDirectories(packagesDir.FullName).Length); Assert.Equal(3, lockFile.PackageFolders.Count); Assert.Equal(packagesDir.FullName, lockFile.PackageFolders[0].Path); Assert.Equal(fallbackFolder.FullName, lockFile.PackageFolders[1].Path); Assert.Equal(fallbackFolder2.FullName, lockFile.PackageFolders[2].Path); } }
public async Task CompatilibityChecker_SingleFileVerifyCompatibility(string file, bool expected) { // Arrange var sources = new List <PackageSource>(); var project1Json = @" { ""version"": ""1.0.0"", ""description"": """", ""authors"": [ ""author"" ], ""tags"": [ """" ], ""projectUrl"": """", ""licenseUrl"": """", ""frameworks"": { ""netstandard1.5"": { ""dependencies"": { ""packageA"": { ""version"": ""1.0.0"" } } } } }"; using (var workingDir = TestDirectory.Create()) { var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages")); var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource")); var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1")); packagesDir.Create(); packageSource.Create(); project1.Create(); sources.Add(new PackageSource(packageSource.FullName)); File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json); var specPath1 = Path.Combine(project1.FullName, "project.json"); var spec1 = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1); var logger = new TestLogger(); var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger); request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json"); request.RequestedRuntimes.Add("win7-x86"); var packageA = new SimpleTestPackageContext("packageA"); packageA.AddFile(file); // Ensure that the package doesn't pass due to no ref or lib files. packageA.AddFile("lib/net462/_._"); SimpleTestPackageUtility.CreatePackages(packageSource.FullName, packageA); // Act var command = new RestoreCommand(request); var result = await command.ExecuteAsync(); await result.CommitAsync(logger, CancellationToken.None); // Assert Assert.Equal(expected, result.Success); // Verify both libraries were installed Assert.Equal(1, result.LockFile.Libraries.Count); // Verify no compatibility issues Assert.Equal(expected, result.CompatibilityCheckResults.All(check => check.Success)); } }
public async Task UWPRestore_BlankUWPApp() { // Arrange var sources = new List <PackageSource>(); sources.Add(new PackageSource("https://api.nuget.org/v3/index.json")); using (var packagesDir = TestDirectory.Create()) using (var projectDir = TestDirectory.Create()) using (var cacheContext = new SourceCacheContext()) { var configJson = JObject.Parse(@"{ ""dependencies"": { ""Microsoft.NETCore.UniversalWindowsPlatform"": ""5.0.0"" }, ""frameworks"": { ""uap10.0"": {} }, ""runtimes"": { ""win10-arm"": {}, ""win10-arm-aot"": {}, ""win10-x86"": {}, ""win10-x86-aot"": {}, ""win10-x64"": {}, ""win10-x64-aot"": {} } }"); var specPath = Path.Combine(projectDir, "TestProject", "project.json"); var spec = JsonPackageSpecReader.GetPackageSpec(configJson.ToString(), "TestProject", specPath); var logger = new TestLogger(); var request = new TestRestoreRequest(spec, sources, packagesDir, cacheContext, logger); request.LockFilePath = Path.Combine(projectDir, "project.lock.json"); var lockFileFormat = new LockFileFormat(); var command = new RestoreCommand(request); var expectedStream = GetResource("NuGet.Commands.FuncTest.compiler.resources.uwpBlankAppV2.json"); JObject expectedJson = null; using (var reader = new StreamReader(expectedStream)) { expectedJson = JObject.Parse(reader.ReadToEnd()); } // Act var result = await command.ExecuteAsync(); await result.CommitAsync(logger, CancellationToken.None); var lockFileJson = JObject.Parse(File.OpenText(request.LockFilePath).ReadToEnd()); RemovePackageFolders(lockFileJson); // Assert Assert.True(result.Success); Assert.Equal(0, result.CompatibilityCheckResults.Sum(checkResult => checkResult.Issues.Count)); Assert.Equal(0, logger.Errors); Assert.Equal(0, logger.Warnings); Assert.Equal(118, result.GetAllInstalled().Count); // TODO: skipping comparing assets file since NuGet.org is doing repo sign for all the existing // packages which is changing the sha512 in the assets file which fails the comparison. // We should enable it once all the packages are repo signed. // tracking issue# https://github.com/NuGet/Home/issues/7361 //Assert.Equal(expectedJson.ToString(), lockFileJson.ToString()); } }
/// <summary> /// Fetch, if not already downloaded, and install the package represented by /// (<paramref name="packageId"/>, <paramref name="version"/>). /// </summary> /// <remarks>It is safe to call it concurrently be cause we operations are done using the FileLock.</remarks> /// <param name="packageId">Name of package to install.</param> /// <param name="version">Version of package to install.</param> public async Task <NugetLocalPackage> InstallPackage(string packageId, PackageVersion version, IEnumerable <string> targetFrameworks, ProgressReport progress) { using (GetLocalRepositoryLock()) { currentProgressReport = progress; try { var identity = new PackageIdentity(packageId, version.ToNuGetVersion()); var resolutionContext = new ResolutionContext( DependencyBehavior.Lowest, true, true, VersionConstraints.None); var repositories = PackageSources.Select(sourceRepositoryProvider.CreateRepository).ToArray(); var projectContext = new EmptyNuGetProjectContext() { ActionType = NuGetActionType.Install, PackageExtractionContext = new PackageExtractionContext(PackageSaveMode.Defaultv3, XmlDocFileSaveMode.Skip, null, NativeLogger), }; ActivityCorrelationId.StartNew(); { var installPath = SettingsUtility.GetGlobalPackagesFolder(settings); // In case it's a package without any TFM (i.e. Visual Studio plugin), we still need to specify one if (!targetFrameworks.Any()) { targetFrameworks = new string[] { "net6.0" } } ; // Old version expects to be installed in GamePackages if (packageId == "Xenko" && version < new PackageVersion(3, 0, 0, 0) && oldRootDirectory != null) { installPath = oldRootDirectory; } var projectPath = Path.Combine("StrideLauncher.json"); var spec = new PackageSpec() { Name = Path.GetFileNameWithoutExtension(projectPath), // make sure this package never collides with a dependency FilePath = projectPath, Dependencies = new List <LibraryDependency>() { new LibraryDependency { LibraryRange = new LibraryRange(packageId, new VersionRange(version.ToNuGetVersion()), LibraryDependencyTarget.Package), } }, RestoreMetadata = new ProjectRestoreMetadata { ProjectPath = projectPath, ProjectName = Path.GetFileNameWithoutExtension(projectPath), ProjectStyle = ProjectStyle.PackageReference, ProjectUniqueName = projectPath, OutputPath = Path.Combine(Path.GetTempPath(), $"StrideLauncher-{packageId}-{version.ToString()}"), OriginalTargetFrameworks = targetFrameworks.ToList(), ConfigFilePaths = settings.GetConfigFilePaths(), PackagesPath = installPath, Sources = SettingsUtility.GetEnabledSources(settings).ToList(), FallbackFolders = SettingsUtility.GetFallbackPackageFolders(settings).ToList() }, }; foreach (var targetFramework in targetFrameworks) { spec.TargetFrameworks.Add(new TargetFrameworkInformation { FrameworkName = NuGetFramework.Parse(targetFramework) }); } using (var context = new SourceCacheContext { MaxAge = DateTimeOffset.UtcNow }) { context.IgnoreFailedSources = true; var dependencyGraphSpec = new DependencyGraphSpec(); dependencyGraphSpec.AddProject(spec); dependencyGraphSpec.AddRestore(spec.RestoreMetadata.ProjectUniqueName); IPreLoadedRestoreRequestProvider requestProvider = new DependencyGraphSpecRequestProvider(new RestoreCommandProvidersCache(), dependencyGraphSpec); var restoreArgs = new RestoreArgs { AllowNoOp = true, CacheContext = context, CachingSourceProvider = new CachingSourceProvider(new PackageSourceProvider(settings)), Log = NativeLogger, }; // Create requests from the arguments var requests = requestProvider.CreateRequests(restoreArgs).Result; foreach (var request in requests) { // Limit concurrency to avoid timeout request.Request.MaxDegreeOfConcurrency = 4; var command = new RestoreCommand(request.Request); // Act var result = await command.ExecuteAsync(); if (!result.Success) { throw new InvalidOperationException($"Could not restore package {packageId}"); } foreach (var install in result.RestoreGraphs.Last().Install) { var package = result.LockFile.Libraries.FirstOrDefault(x => x.Name == install.Library.Name && x.Version == install.Library.Version); if (package != null) { var packagePath = Path.Combine(installPath, package.Path); OnPackageInstalled(this, new PackageOperationEventArgs(new PackageName(install.Library.Name, install.Library.Version.ToPackageVersion()), packagePath)); } } } } if (packageId == "Xenko" && version < new PackageVersion(3, 0, 0, 0)) { UpdateTargetsHelper(); } } // Load the recently installed package var installedPackages = GetPackagesInstalled(new[] { packageId }); return(installedPackages.FirstOrDefault(p => p.Version == version)); } finally { currentProgressReport = null; } } }
public async Task ProjectResolution_MSBuildProjectDoesNotResolveByDirectory() { // Arrange var sources = new List <PackageSource>(); var project1Json = @" { ""version"": ""1.0.0-*"", ""description"": """", ""authors"": [ ""author"" ], ""tags"": [ """" ], ""projectUrl"": """", ""licenseUrl"": """", ""dependencies"": { ""project2"": ""1.0.0-*"" }, ""frameworks"": { ""net45"": { } } }"; var project2Json = @" { ""version"": ""1.0.0-*"", ""description"": """", ""authors"": [ ""author"" ], ""tags"": [ """" ], ""projectUrl"": """", ""licenseUrl"": """", ""frameworks"": { ""net45"": { } } }"; var globalJson = @" { ""projects"": [ ""projects"" ] }"; using (var workingDir = TestDirectory.Create()) { var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages")); var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource")); var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1")); var project2 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project2")); packagesDir.Create(); packageSource.Create(); project1.Create(); project2.Create(); File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json); File.WriteAllText(Path.Combine(project2.FullName, "project.json"), project2Json); File.WriteAllText(Path.Combine(workingDir, "global.json"), globalJson); var project1CSProjPath = Path.Combine(project1.FullName, "project1.csproj"); File.WriteAllText(project1CSProjPath, string.Empty); var specPath1 = Path.Combine(project1.FullName, "project.json"); var specPath2 = Path.Combine(project2.FullName, "project.json"); var spec1 = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1).EnsureProjectJsonRestoreMetadata(); var spec2 = JsonPackageSpecReader.GetPackageSpec(project2Json, "project2", specPath2).EnsureProjectJsonRestoreMetadata(); var logger = new TestLogger(); var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger); request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json"); request.ExternalProjects.Add( new ExternalProjectReference("project1", spec1, project1CSProjPath, new string[] { })); // Act var command = new RestoreCommand(request); var result = await command.ExecuteAsync(); var lockFile = result.LockFile; await result.CommitAsync(logger, CancellationToken.None); // Assert Assert.False(result.Success); Assert.Equal(1, result.GetAllUnresolved().Count); Assert.Equal("project2", result.GetAllUnresolved().Single().Name); } }
private async Task<bool> Restore(PublishRoot root, PublishProject publishProject, string restoreDirectory) { var appEnv = (IApplicationEnvironment)root.HostServices.GetService(typeof(IApplicationEnvironment)); var feedOptions = new FeedOptions(); feedOptions.IgnoreFailedSources = true; feedOptions.Sources.Add(root.TargetPackagesPath); feedOptions.TargetPackagesFolder = root.TargetPackagesPath; var restoreCommand = new RestoreCommand(appEnv); foreach (var framework in root.Frameworks) { restoreCommand.TargetFrameworks.Add(framework.Key); } restoreCommand.SkipRestoreEvents = true; restoreCommand.SkipInstall = true; // This is a workaround for #1322. Since we use restore to generate the lock file // after publish, it's possible to fail restore after copying the closure // if framework assemblies and packages have the same name. This is more likely now // since dependencies may exist in the top level restoreCommand.IgnoreMissingDependencies = true; restoreCommand.CheckHashFile = false; restoreCommand.RestoreDirectories.Add(restoreDirectory); restoreCommand.FeedOptions = feedOptions; // Mute "dnu restore" subcommand restoreCommand.Reports = Reports.Constants.NullReports; var success = await restoreCommand.Execute(); return success; }
public InstallCommand(AddCommand addCmd, RestoreCommand restoreCmd) { _addCommand = addCmd; _restoreCommand = restoreCmd; }
private bool UpdateLockFile(PublishRoot root) { var appEnv = (IApplicationEnvironment)root.HostServices.GetService(typeof(IApplicationEnvironment)); var feedOptions = new FeedOptions(); feedOptions.IgnoreFailedSources = true; feedOptions.Sources.Add(root.TargetPackagesPath); feedOptions.TargetPackagesFolder = root.TargetPackagesPath; var tasks = new Task<bool>[root.Projects.Count]; for (int i = 0; i < root.Projects.Count; i++) { var project = root.Projects[i]; var restoreCommand = new RestoreCommand(appEnv); foreach (var runtime in root.Runtimes) { restoreCommand.TargetFrameworks.Add(project.SelectFrameworkForRuntime(runtime)); } var restoreDirectory = project.IsPackage ? Path.Combine(project.TargetPath, "root") : project.TargetPath; restoreCommand.SkipRestoreEvents = true; restoreCommand.SkipInstall = true; // This is a workaround for #1322. Since we use restore to generate the lock file // after publish, it's possible to fail restore after copying the closure // if framework assemblies and packages have the same name. This is more likely now // since dependencies may exist in the top level restoreCommand.IgnoreMissingDependencies = true; restoreCommand.CheckHashFile = false; restoreCommand.RestoreDirectories.Add(restoreDirectory); restoreCommand.FeedOptions = feedOptions; restoreCommand.Reports = root.Reports.ShallowCopy(); // Mute "dnu restore" completely if it is invoked by "dnu publish --quiet" restoreCommand.Reports.Information = root.Reports.Quiet; tasks[i] = restoreCommand.Execute(); } Task.WaitAll(tasks); return tasks.All(t => t.Result); }
public ICommand CreateCommand(ScriptCsArgs args) { if (args.ScriptName != null) { var executeCommand = new ExecuteScriptCommand( args.ScriptName, _scriptServiceRoot.FileSystem, _scriptServiceRoot.Executor, _scriptServiceRoot.ScriptPackResolver); if (args.Restore) { var restoreCommand = new RestoreCommand( args.ScriptName, _scriptServiceRoot.FileSystem, _scriptServiceRoot.PackageAssemblyResolver); return new CompositeCommand(restoreCommand, executeCommand); } return executeCommand; } if (args.Install != null) { var installCommand = new InstallCommand( args.Install, args.AllowPreReleaseFlag, _scriptServiceRoot.FileSystem, _scriptServiceRoot.PackageAssemblyResolver, _scriptServiceRoot.PackageInstaller); var restoreCommand = new RestoreCommand( args.Install, _scriptServiceRoot.FileSystem, _scriptServiceRoot.PackageAssemblyResolver); return new CompositeCommand(installCommand, restoreCommand); } if (args.Clean) { var cleanCommand = new CleanCommand( args.ScriptName, _scriptServiceRoot.FileSystem, _scriptServiceRoot.PackageAssemblyResolver); return cleanCommand; } if (args.Save) { return new SaveCommand(_scriptServiceRoot.PackageAssemblyResolver); } if (args.Version) { return new VersionCommand(); } return new InvalidCommand(); }
public async Task RestoreSemVer_RestorePackageFloatOnReleaseLabelAsync() { // Arrange var sources = new List <PackageSource>(); var project1Json = @" { ""version"": ""1.0.0"", ""description"": """", ""authors"": [ ""author"" ], ""tags"": [ """" ], ""projectUrl"": """", ""licenseUrl"": """", ""frameworks"": { ""netstandard1.5"": { ""dependencies"": { ""packageA"": ""1.0.0-alpha.1.*"" } } } }"; using (var workingDir = TestDirectory.Create()) { var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages")); var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource")); var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1")); packagesDir.Create(); packageSource.Create(); project1.Create(); sources.Add(new PackageSource(packageSource.FullName)); File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json); var specPath1 = Path.Combine(project1.FullName, "project.json"); var spec1 = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1); var logger = new TestLogger(); var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger) { LockFilePath = Path.Combine(project1.FullName, "project.lock.json") }; var packages = new List <SimpleTestPackageContext>(); var package1 = new SimpleTestPackageContext("packageA") { Version = "1.0.0-alpha.1.10.1" }; package1.AddFile("lib/netstandard1.5/a.dll"); packages.Add(package1); var package2 = new SimpleTestPackageContext("packageA") { Version = "1.0.0-alpha.1.11.1" }; package2.AddFile("lib/netstandard1.5/a.dll"); packages.Add(package2); var package3 = new SimpleTestPackageContext("packageA") { Version = "1.0.0-alpha.1.9.2" }; package3.AddFile("lib/netstandard1.5/a.dll"); packages.Add(package3); var package4 = new SimpleTestPackageContext("packageA") { Version = "1.0.0-alpha.1" }; package4.AddFile("lib/netstandard1.5/a.dll"); packages.Add(package4); var package5 = new SimpleTestPackageContext("packageA") { Version = "1.0.0-beta.1.99" }; package5.AddFile("lib/netstandard1.5/a.dll"); packages.Add(package5); var package6 = new SimpleTestPackageContext("packageA") { Version = "1.0.0-alpha.2.99" }; package6.AddFile("lib/netstandard1.5/a.dll"); packages.Add(package6); var package7 = new SimpleTestPackageContext("packageA") { Version = "1.0.0-alpha.1.2+skip" }; package7.AddFile("lib/netstandard1.5/a.dll"); packages.Add(package7); await SimpleTestPackageUtility.CreatePackagesAsync(packages, packageSource.FullName); // Act var command = new RestoreCommand(request); var result = await command.ExecuteAsync(); var lockFile = result.LockFile; await result.CommitAsync(logger, CancellationToken.None); var targetLib = lockFile.GetTarget(NuGetFramework.Parse("netstandard1.5"), null) .Libraries .Single(library => library.Name == "packageA"); var compile = targetLib.CompileTimeAssemblies.Single(); // Assert Assert.True(result.Success); Assert.Equal("lib/netstandard1.5/a.dll", compile.Path); Assert.Equal("1.0.0-alpha.1.11.1", targetLib.Version.ToNormalizedString()); } }
private void TestProject(string projectFolderOrFile, string testName, ProjectPerfOperation perfOperation, string restoreSources = null) { string testProjectPath; string testProjectDirectory; bool projectFileSpecified; if (File.Exists(projectFolderOrFile)) { projectFileSpecified = true; testProjectPath = projectFolderOrFile; testProjectDirectory = Path.GetDirectoryName(projectFolderOrFile); } else { projectFileSpecified = false; testProjectPath = Directory.GetFiles(projectFolderOrFile, "*.sln", SearchOption.AllDirectories).SingleOrDefault(); if (testProjectPath == null) { testProjectPath = Directory.GetFiles(projectFolderOrFile, "*.csproj", SearchOption.AllDirectories).SingleOrDefault(); if (testProjectPath == null) { throw new ArgumentException("Could not find project file to test in folder: " + projectFolderOrFile); } } testProjectDirectory = Path.GetDirectoryName(testProjectPath); } TestCommand commandToTest; var perfTest = new PerfTest(); perfTest.ScenarioName = testName; if (perfOperation == ProjectPerfOperation.NoOpRestore) { TestCommand restoreCommand; if (TestContext.Current.ToolsetUnderTest.ShouldUseFullFrameworkMSBuild) { restoreCommand = new RestoreCommand(Log, testProjectPath); } else { restoreCommand = new RestoreCommand(Log, testProjectPath); restoreCommand = new DotnetCommand(Log, "restore"); if (projectFileSpecified) { restoreCommand.Arguments.Add(testProjectPath); } } if (!string.IsNullOrEmpty(restoreSources)) { restoreCommand.Arguments.Add($"/p:RestoreSources={restoreSources}"); } restoreCommand.WorkingDirectory = testProjectDirectory; restoreCommand.Execute().Should().Pass(); commandToTest = restoreCommand; perfTest.TestName = "Restore (No-op)"; } else { if (TestContext.Current.ToolsetUnderTest.ShouldUseFullFrameworkMSBuild) { commandToTest = new BuildCommand(Log, projectFileSpecified ? testProjectPath : testProjectDirectory); commandToTest.Arguments.Add("/restore"); } else { commandToTest = new DotnetCommand(Log, "build"); if (projectFileSpecified) { commandToTest.Arguments.Add(testProjectPath); } } if (!string.IsNullOrEmpty(restoreSources)) { commandToTest.Arguments.Add($"/p:RestoreSources={restoreSources}"); } commandToTest.WorkingDirectory = testProjectDirectory; if (perfOperation == ProjectPerfOperation.CleanBuild) { perfTest.TestName = "Build"; } else if (perfOperation == ProjectPerfOperation.BuildWithNoChanges) { // Build once before taking folder snaspshot commandToTest.Execute().Should().Pass(); perfTest.TestName = "Build (no changes)"; } else { throw new ArgumentException("Unexpected perf operation: " + perfOperation); } } perfTest.ProcessToMeasure = commandToTest.GetProcessStartInfo(); perfTest.TestFolder = testProjectDirectory; perfTest.Run(); }
public async Task RestoreSemVer_RestorePackageWithMetadata_DifferentMetadataDoesNotMatter() { // Arrange var sources = new List <PackageSource>(); var project1Json = @" { ""version"": ""1.0.0"", ""description"": """", ""authors"": [ ""author"" ], ""tags"": [ """" ], ""projectUrl"": """", ""licenseUrl"": """", ""frameworks"": { ""netstandard1.5"": { ""dependencies"": { ""packageA"": ""1.0.0+1"" } } } }"; using (var workingDir = TestDirectory.Create()) { var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages")); var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource")); var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1")); packagesDir.Create(); packageSource.Create(); project1.Create(); sources.Add(new PackageSource(packageSource.FullName)); File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json); var specPath1 = Path.Combine(project1.FullName, "project.json"); var spec1 = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1); var logger = new TestLogger(); var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger); request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json"); var packageAContext = new SimpleTestPackageContext("packageA") { Version = "1.0.0+B" }; packageAContext.AddFile("lib/netstandard1.5/a.dll"); SimpleTestPackageUtility.CreateFullPackage(packageSource.FullName, packageAContext); // Act var command = new RestoreCommand(request); var result = await command.ExecuteAsync(); var lockFile = result.LockFile; await result.CommitAsync(logger, CancellationToken.None); var targetLib = lockFile.GetTarget(NuGetFramework.Parse("netstandard1.5"), null) .Libraries .Single(library => library.Name == "packageA"); var compile = targetLib.CompileTimeAssemblies.Single(); // Assert Assert.True(result.Success); Assert.Equal("lib/netstandard1.5/a.dll", compile.Path); Assert.Equal("1.0.0", targetLib.Version.ToNormalizedString()); } }
public async Task Project2ProjectInLockFile_VerifySnapshotVersions() { // Arrange var sources = new List <PackageSource>(); var projectJson = @" { ""version"": ""2.0.0"", ""dependencies"": { }, ""frameworks"": { ""net45"": {} } }"; var project2Json = @" { ""version"": ""2.0.0-*"", ""description"": ""Proj2 Class Library"", ""authors"": [ ""author"" ], ""tags"": [ """" ], ""projectUrl"": """", ""licenseUrl"": """", ""dependencies"": { ""project3"": ""2.0.0-*"" }, ""frameworks"": { ""net45"": { } } }"; var project3Json = @" { ""version"": ""2.0.0-*"", ""description"": ""Proj3 Class Library"", ""authors"": [ ""author"" ], ""tags"": [ """" ], ""projectUrl"": """", ""licenseUrl"": """", ""frameworks"": { ""net45"": { } } }"; var globalJson = @" { ""projects"": [ ""projects"" ] }"; using (var packagesDir = TestDirectory.Create()) using (var workingDir = TestDirectory.Create()) { var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1")); var project2 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project2")); var project3 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project3")); project1.Create(); project2.Create(); project3.Create(); File.WriteAllText(Path.Combine(project1.FullName, "project.json"), projectJson); File.WriteAllText(Path.Combine(project2.FullName, "project.json"), project2Json); File.WriteAllText(Path.Combine(project3.FullName, "project.json"), project3Json); File.WriteAllText(Path.Combine(workingDir, "global.json"), globalJson); File.WriteAllText(Path.Combine(project1.FullName, "project1.csproj"), string.Empty); File.WriteAllText(Path.Combine(project2.FullName, "project2.xproj"), string.Empty); File.WriteAllText(Path.Combine(project2.FullName, "project3.xproj"), string.Empty); var specPath1 = Path.Combine(project1.FullName, "project.json"); var specPath2 = Path.Combine(project2.FullName, "project.json"); var specPath3 = Path.Combine(project3.FullName, "project.json"); var spec1 = JsonPackageSpecReader.GetPackageSpec(projectJson, "project1", specPath1); var spec2 = JsonPackageSpecReader.GetPackageSpec(project2Json, "project2", specPath2); var spec3 = JsonPackageSpecReader.GetPackageSpec(project3Json, "project3", specPath3); var logger = new TestLogger(); var request = new TestRestoreRequest(spec1, sources, packagesDir, logger); request.ExternalProjects.Add(new ExternalProjectReference( "project1", spec1, Path.Combine(project1.FullName, "project1.csproj"), new string[] { "project2" })); request.ExternalProjects.Add(new ExternalProjectReference( "project2", spec2, Path.Combine(project2.FullName, "project2.xproj"), new string[] { "project3" })); request.ExternalProjects.Add(new ExternalProjectReference( "project3", spec3, Path.Combine(project2.FullName, "project3.xproj"), new string[] { })); request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json"); var format = new LockFileFormat(); // Act var command = new RestoreCommand(request); var result = await command.ExecuteAsync(); await result.CommitAsync(logger, CancellationToken.None); var lockFile = format.Read(request.LockFilePath, logger); var project2Lib = lockFile.GetLibrary("project2", NuGetVersion.Parse("2.0.0")); var project3Lib = lockFile.GetLibrary("project3", NuGetVersion.Parse("2.0.0")); var project2Target = lockFile.GetTarget(FrameworkConstants.CommonFrameworks.Net45, runtimeIdentifier: null) .Libraries .Single(lib => lib.Name == "project2"); var project3Target = lockFile.GetTarget(FrameworkConstants.CommonFrameworks.Net45, runtimeIdentifier: null) .Libraries .Single(lib => lib.Name == "project3"); // Assert Assert.True(result.Success); Assert.Equal("2.0.0", project2Target.Version.ToString()); Assert.Equal("2.0.0", project3Target.Version.ToString()); Assert.Equal("2.0.0", project2Lib.Version.ToString()); Assert.Equal("2.0.0", project3Lib.Version.ToString()); Assert.Equal("2.0.0", project2Target.Dependencies.Single().VersionRange.ToLegacyShortString()); } }
public InstallGlobalCommand(IApplicationEnvironment env, IAppCommandsRepository commandsRepository) { RestoreCommand = new RestoreCommand(env); _commandsRepository = commandsRepository; }
public async Task UWPRestore_BlankUWPAppWithExcludes() { // Arrange var sources = new List <PackageSource>(); sources.Add(new PackageSource("https://api.nuget.org/v3/index.json")); using (var packagesDir = TestDirectory.Create()) using (var projectDir = TestDirectory.Create()) using (var cacheContext = new SourceCacheContext()) { var configJson = JObject.Parse(@"{ ""dependencies"": { ""Microsoft.NETCore.UniversalWindowsPlatform"": { ""version"": ""5.0.0"", ""exclude"": ""build,runtime,compile,native"" } }, ""frameworks"": { ""uap10.0"": {} }, ""runtimes"": { ""win10-arm"": {}, ""win10-arm-aot"": {}, ""win10-x86"": {}, ""win10-x86-aot"": {}, ""win10-x64"": {}, ""win10-x64-aot"": {} } }"); var specPath = Path.Combine(projectDir, "TestProject", "project.json"); var spec = JsonPackageSpecReader.GetPackageSpec(configJson.ToString(), "TestProject", specPath); var logger = new TestLogger(); var extractionContext = new PackageExtractionContext( PackageSaveMode.Defaultv3, PackageExtractionBehavior.XmlDocFileSaveMode, ClientPolicyContext.GetClientPolicy(NullSettings.Instance, logger), logger); var request = new TestRestoreRequest(spec, sources, packagesDir, cacheContext, extractionContext, logger) { LockFilePath = Path.Combine(projectDir, "project.lock.json") }; var lockFileFormat = new LockFileFormat(); var command = new RestoreCommand(request); // Act var result = await command.ExecuteAsync(); await result.CommitAsync(logger, CancellationToken.None); var lockFileJson = JObject.Parse(File.OpenText(request.LockFilePath).ReadToEnd()); // Assert Assert.Equal(0, result.CompatibilityCheckResults.Sum(checkResult => checkResult.Issues.Count)); Assert.Equal(0, logger.Errors); Assert.Equal(0, logger.Warnings); Assert.Equal(118, result.GetAllInstalled().Count); } }
public async Task MinClientVersion_DependencyVersionTooHighAsync() { // Arrange var sources = new List <PackageSource>(); var project1Json = @" { ""version"": ""1.0.0"", ""description"": """", ""authors"": [ ""author"" ], ""tags"": [ """" ], ""projectUrl"": """", ""licenseUrl"": """", ""frameworks"": { ""netstandard1.3"": { ""dependencies"": { ""packageA"": ""1.0.0"" } } } }"; using (var workingDir = TestDirectory.Create()) { var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages")); var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource")); var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1")); packagesDir.Create(); packageSource.Create(); project1.Create(); sources.Add(new PackageSource(packageSource.FullName)); File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json); var specPath1 = Path.Combine(project1.FullName, "project.json"); var spec1 = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1); var logger = new TestLogger(); var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger) { LockFilePath = Path.Combine(project1.FullName, "project.lock.json") }; var packageBContext = new SimpleTestPackageContext() { Id = "packageB", Version = "1.0.0", MinClientVersion = "9.0.0" }; var packageAContext = new SimpleTestPackageContext() { Id = "packageA", Version = "1.0.0", MinClientVersion = "1.0.0", Dependencies = new List <SimpleTestPackageContext>() { packageBContext } }; await SimpleTestPackageUtility.CreatePackagesAsync(packageSource.FullName, packageAContext, packageBContext); Exception ex = null; // Act var command = new RestoreCommand(request); try { var result = await command.ExecuteAsync(); } catch (Exception exception) { ex = exception; } // Assert Assert.Contains("The 'packageB 1.0.0' package requires NuGet client version '9.0.0' or above, but the current NuGet version is", ex.Message); } }
private static bool RestoreProject(string pathToRestore) { return(RestoreCommand.Run(new string[] { pathToRestore }) == 0); }
public async Task LockFileBuilderCache_DifferentPackagePath_WillNotCache(bool differentPath, bool cachingIsExpected) { // Arrange using (var tmpPath = new SimpleTestPathContext()) { var packageA = new SimpleTestPackageContext { Id = "PackageA", Version = "1.0.0", }; var logger = new TestLogger(); var lockFileBuilderCache = new LockFileBuilderCache(); var project1Directory = new DirectoryInfo(Path.Combine(tmpPath.SolutionRoot, "Library1")); var project2Directory = new DirectoryInfo(Path.Combine(tmpPath.SolutionRoot, "Library2")); var globalPackages1 = new DirectoryInfo(Path.Combine(tmpPath.WorkingDirectory, "globalPackages1")); var globalPackages2 = new DirectoryInfo(Path.Combine(tmpPath.WorkingDirectory, "globalPackages2")); var packageSource = new DirectoryInfo(Path.Combine(tmpPath.WorkingDirectory, "packageSource")); globalPackages1.Create(); globalPackages2.Create(); packageSource.Create(); var project1Spec = PackageReferenceSpecBuilder.Create("Library1", project1Directory.FullName) .WithTargetFrameworks(new[] { new TargetFrameworkInformation { FrameworkName = NuGetFramework.Parse("net471"), Dependencies = new List <LibraryDependency>( new[] { new LibraryDependency { LibraryRange = new LibraryRange("PackageA", VersionRange.Parse("1.0.0"), LibraryDependencyTarget.All) }, }) } }) .Build(); var project2Spec = PackageReferenceSpecBuilder.Create("Library2", project2Directory.FullName) .WithTargetFrameworks(new[] { new TargetFrameworkInformation { FrameworkName = NuGetFramework.Parse("net471"), Dependencies = new List <LibraryDependency>( new[] { new LibraryDependency { LibraryRange = new LibraryRange("PackageA", VersionRange.Parse("1.0.0"), LibraryDependencyTarget.All) }, }) } }) .Build(); var sources = new[] { new PackageSource(packageSource.FullName) } .Select(source => Repository.Factory.GetCoreV3(source)) .ToList(); var request1 = new TestRestoreRequest( project1Spec, sources, globalPackages1.FullName, new List <string>(), new TestSourceCacheContext(), ClientPolicyContext.GetClientPolicy(NullSettings.Instance, logger), logger, lockFileBuilderCache ) { LockFilePath = Path.Combine(project1Directory.FullName, "project.lock.json") }; var request2 = new TestRestoreRequest( project2Spec, sources, differentPath ? globalPackages2.FullName : globalPackages1.FullName, new List <string>(), new TestSourceCacheContext(), ClientPolicyContext.GetClientPolicy(NullSettings.Instance, logger), logger, lockFileBuilderCache ) { LockFilePath = Path.Combine(project2Directory.FullName, "project.lock.json") }; await SimpleTestPackageUtility.CreatePackagesAsync( packageSource.FullName, packageA); // Act var command1 = new RestoreCommand(request1); var result1 = await command1.ExecuteAsync(); var lockFile1 = result1.LockFile; var command2 = new RestoreCommand(request2); var result2 = await command2.ExecuteAsync(); var lockFile2 = result2.LockFile; // Assert Assert.True(result1.Success); Assert.Equal(1, lockFile1.Libraries.Count); Assert.Equal(1, lockFile1.Targets.Single().Libraries.Count); Assert.True(result2.Success); Assert.Equal(1, lockFile2.Libraries.Count); Assert.Equal(1, lockFile2.Targets.Single().Libraries.Count); // Check whether packageA comes from the cache var lockFile1TargetLibraryA = lockFile1.Targets.Single().Libraries.Single(x => x.Name == "PackageA"); var lockFile2TargetLibraryA = lockFile2.Targets.Single().Libraries.Single(x => x.Name == "PackageA"); Assert.Equal(cachingIsExpected, ReferenceEquals(lockFile1TargetLibraryA, lockFile2TargetLibraryA)); } }
public async Task RestoreTargets_RestoreWithNoRuntimes() { // Arrange var sources = new List <PackageSource>(); var project1Json = @" { ""version"": ""1.0.0"", ""description"": """", ""authors"": [ ""author"" ], ""tags"": [ """" ], ""projectUrl"": """", ""licenseUrl"": """", ""frameworks"": { ""netstandard1.5"": { ""dependencies"": { ""packageA"": ""1.0.0"" } } } }"; using (var workingDir = TestFileSystemUtility.CreateRandomTestFolder()) { var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages")); var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource")); var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1")); packagesDir.Create(); packageSource.Create(); project1.Create(); sources.Add(new PackageSource(packageSource.FullName)); File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json); var specPath1 = Path.Combine(project1.FullName, "project.json"); var spec1 = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1); var logger = new TestLogger(); var request = new RestoreRequest(spec1, sources, packagesDir.FullName, logger); request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json"); var packageA = new SimpleTestPackageContext() { Id = "packageA" }; packageA.AddFile("lib/a.dll"); packageA.AddFile("lib/netstandard1.5/a.dll"); packageA.AddFile("lib/netstandard1.5/en-us/a.resource.dll"); packageA.AddFile("native/a.dll"); packageA.AddFile("ref/netstandard1.5/a.dll"); packageA.AddFile("contentFiles/any/any/a.dll"); SimpleTestPackageUtility.CreatePackages(packageSource.FullName, packageA); // Act var command = new RestoreCommand(request); var result = await command.ExecuteAsync(); var lockFile = result.LockFile; await result.CommitAsync(logger, CancellationToken.None); var targetLib = lockFile.Targets.Single(graph => graph.RuntimeIdentifier == null).Libraries.Single(); // Assert Assert.True(result.Success); Assert.Equal(1, lockFile.Libraries.Count); Assert.Equal(0, targetLib.RuntimeTargets.Count); } }
public async Task DependencyTypeConstraint_TargetPackage() { // Arrange var sources = new List <PackageSource>(); var project1Json = @" { ""version"": ""1.0.0"", ""description"": """", ""authors"": [ ""author"" ], ""tags"": [ """" ], ""projectUrl"": """", ""licenseUrl"": """", ""dependencies"": { ""packageA"": { ""version"": ""1.0.0"", ""target"": ""package"" } }, ""frameworks"": { ""net45"": { } } }"; var packageAProjectJson = @" { ""version"": ""1.0.0"", ""description"": """", ""authors"": [ ""author"" ], ""tags"": [ """" ], ""projectUrl"": """", ""licenseUrl"": """", ""frameworks"": { ""net45"": { } } }"; using (var workingDir = TestDirectory.Create()) { var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages")); var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource")); var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1")); var packageAProject = new DirectoryInfo(Path.Combine(workingDir, "projects", "packageA")); var packageAExternalProject = new DirectoryInfo(Path.Combine(workingDir, "external", "packageA")); packagesDir.Create(); packageSource.Create(); project1.Create(); packageAProject.Create(); packageAExternalProject.Create(); sources.Add(new PackageSource(packageSource.FullName)); File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json); File.WriteAllText(Path.Combine(packageAProject.FullName, "project.json"), packageAProjectJson); var project1ProjPath = Path.Combine(project1.FullName, "project1.xproj"); File.WriteAllText(project1ProjPath, string.Empty); File.WriteAllText(Path.Combine(packageAProject.FullName, "packageA.xproj"), string.Empty); var specPath1 = Path.Combine(project1.FullName, "project.json"); var specPath2 = Path.Combine(packageAProject.FullName, "project.json"); var spec1 = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1); var spec2 = JsonPackageSpecReader.GetPackageSpec(packageAProjectJson, "packageA", specPath2); var packageAPath = SimpleTestPackageUtility.CreateFullPackage( packageSource.FullName, "packageA", "1.0.0"); await GlobalFolderUtility.AddPackageToGlobalFolderAsync(packageAPath, packagesDir); var logger = new TestLogger(); var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger); request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json"); // Act var command = new RestoreCommand(request); var result = await command.ExecuteAsync(); var lockFile = result.LockFile; await result.CommitAsync(logger, CancellationToken.None); var packageALib = lockFile.GetLibrary("packageA", NuGetVersion.Parse("1.0.0")); var packageATarget = lockFile.GetTarget( FrameworkConstants.CommonFrameworks.Net45, runtimeIdentifier: null) .Libraries .Single(lib => lib.Name == "packageA"); // Assert Assert.True(result.Success); Assert.Equal(LibraryType.Package, packageALib.Type); Assert.Equal(LibraryType.Package, packageATarget.Type); } }
public async Task FallbackFolderRestore_VerifyMissingFallbackFolderFailsAsync() { // Arrange var sources = new List <PackageSource>(); var project1Json = @" { ""version"": ""1.0.0"", ""description"": """", ""authors"": [ ""author"" ], ""tags"": [ """" ], ""projectUrl"": """", ""licenseUrl"": """", ""frameworks"": { ""netstandard1.3"": { ""dependencies"": { ""packageA"": ""1.0.0"", ""packageB"": ""1.0.0"" } } } }"; using (var workingDir = TestDirectory.Create()) { var fallbackFolder = new DirectoryInfo(Path.Combine(workingDir, "fallbackFolder")); var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages")); var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource")); var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1")); packageSource.Create(); project1.Create(); sources.Add(new PackageSource(packageSource.FullName)); File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json); var specPath1 = Path.Combine(project1.FullName, "project.json"); var spec1 = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1).EnsureProjectJsonRestoreMetadata(); var logger = new TestLogger(); var request = new TestRestoreRequest( spec1, sources, packagesDir.FullName, new List <string>() { fallbackFolder.FullName }, logger) { LockFilePath = Path.Combine(project1.FullName, "project.lock.json") }; var packageBContext = new SimpleTestPackageContext() { Id = "packageB", Version = "1.0.0" }; var packageAContext = new SimpleTestPackageContext() { Id = "packageA", Version = "1.0.0" }; await SimpleTestPackageUtility.CreatePackagesAsync( packageSource.FullName, packageAContext, packageBContext); // Act & Assert var command = new RestoreCommand(request); var result = await command.ExecuteAsync(); result.Success.Should().BeFalse(); result.LockFile.LogMessages.Select(e => e.Code).Should().AllBeEquivalentTo(NuGetLogCode.NU1301); } }
public async Task DependencyTypeConstraint_PackagesDependOnProject() { // Arrange var sources = new List <PackageSource>(); var project1Json = @" { ""version"": ""1.0.0"", ""description"": """", ""authors"": [ ""author"" ], ""tags"": [ """" ], ""projectUrl"": """", ""licenseUrl"": """", ""dependencies"": { ""packageA"": ""1.0.0"" }, ""frameworks"": { ""net45"": { } } }"; var packageBProjectJson = @" { ""version"": ""1.0.0"", ""description"": """", ""authors"": [ ""author"" ], ""tags"": [ """" ], ""projectUrl"": """", ""licenseUrl"": """", ""frameworks"": { ""net45"": { } } }"; using (var workingDir = TestDirectory.Create()) { var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages")); var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource")); var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1")); var packageBProject = new DirectoryInfo(Path.Combine(workingDir, "projects", "packageB")); packagesDir.Create(); packageSource.Create(); project1.Create(); packageBProject.Create(); sources.Add(new PackageSource(packageSource.FullName)); File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json); File.WriteAllText(Path.Combine(packageBProject.FullName, "project.json"), packageBProjectJson); var specPath1 = Path.Combine(project1.FullName, "project.json"); var specPath2 = Path.Combine(packageBProject.FullName, "project.json"); var spec1 = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1); var spec2 = JsonPackageSpecReader.GetPackageSpec(packageBProjectJson, "packageB", specPath2); var packageAPath = SimpleTestPackageUtility.CreateFullPackage( packageSource.FullName, "packageA", "1.0.0", new Packaging.Core.PackageDependency[] { new Packaging.Core.PackageDependency("packageB", VersionRange.Parse("1.0.0")) }); await GlobalFolderUtility.AddPackageToGlobalFolderAsync(packageAPath, packagesDir); var logger = new TestLogger(); var restoreContext = new RestoreArgs() { Sources = new List <string>() { packageSource.FullName }, GlobalPackagesFolder = packagesDir.FullName, Log = logger, CacheContext = new SourceCacheContext() }; // Modify specs for netcore spec2 = spec2.WithTestRestoreMetadata(); spec1 = spec1.WithTestRestoreMetadata().WithTestProjectReference(spec2); var request = await ProjectJsonTestHelpers.GetRequestAsync(restoreContext, spec1, spec2); request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json"); // Act var command = new RestoreCommand(request); var result = await command.ExecuteAsync(); var lockFile = result.LockFile; await result.CommitAsync(logger, CancellationToken.None); // Assert Assert.True(result.Success); var packageBLib = lockFile.GetLibrary("packageB", NuGetVersion.Parse("1.0.0")); Assert.NotNull(packageBLib); Assert.Equal(LibraryType.Project, packageBLib.Type); } }
public async Task CompatilibityChecker_RuntimeFoundInSamePackage_SuccessAsync() { // Arrange var sources = new List <PackageSource>(); var project1Json = @" { ""version"": ""1.0.0"", ""description"": """", ""authors"": [ ""author"" ], ""tags"": [ """" ], ""projectUrl"": """", ""licenseUrl"": """", ""frameworks"": { ""netstandard1.5"": { ""dependencies"": { ""packageA"": { ""version"": ""1.0.0"" } } } } }"; using (var workingDir = TestDirectory.Create()) { var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages")); var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource")); var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1")); packagesDir.Create(); packageSource.Create(); project1.Create(); sources.Add(new PackageSource(packageSource.FullName)); File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json); var specPath1 = Path.Combine(project1.FullName, "project.json"); var spec1 = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1); var logger = new TestLogger(); var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger) { LockFilePath = Path.Combine(project1.FullName, "project.lock.json") }; request.RequestedRuntimes.Add("win7-x86"); var packageA = new SimpleTestPackageContext("packageA"); packageA.AddFile("ref/netstandard1.3/a.dll"); packageA.AddFile("ref/netstandard1.3/b.dll"); packageA.AddFile("ref/netstandard1.3/c.dll"); packageA.AddFile("runtimes/win7-x86/lib/netstandard1.1/a.dll"); packageA.AddFile("runtimes/win7-x86/lib/netstandard1.1/b.ni.dll"); packageA.AddFile("runtimes/win7-x86/lib/netstandard1.1/c.dll"); await SimpleTestPackageUtility.CreatePackagesAsync(packageSource.FullName, packageA); // Act var command = new RestoreCommand(request); var result = await command.ExecuteAsync(); await result.CommitAsync(logger, CancellationToken.None); // Assert Assert.True(result.Success, logger.ShowErrors()); // Verify both libraries were installed Assert.Equal(1, result.LockFile.Libraries.Count); // Verify no compatibility issues Assert.True(result.CompatibilityCheckResults.All(check => check.Success)); } }
public async Task RuntimePackage_RejectedPackagesAreNotMerged() { // Arrange var logger = new TestLogger(); var framework = "net46"; using (var workingDir = CreateTestFolders()) { var repository = Path.Combine(workingDir, "repository"); var projectDir = Path.Combine(workingDir, "project"); var packagesDir = Path.Combine(workingDir, "packages"); var runtimeJsonX1 = @"{ ""runtimes"": { ""unix"": { ""packageX"": { ""runtime.packageX"": ""1.0.0"" } } }, ""supports"": { ""x1.app"": { ""uap10.0"": [ ""win10-x86"" ] } } }"; var runtimeJsonX2 = @"{ ""runtimes"": { ""unix"": { ""packageX"": { ""runtime.packageX"": ""2.0.0"" } } }, ""supports"": { ""x2.app"": { ""uap10.0"": [ ""win10-x86"" ] } } }"; var packages = new List <SimpleTestPackageContext>(); // A -> X 1.0.0 -> runtime.X 1.0.0 // B -> X 2.0.0 -> runtime.X 2.0.0 var packageX1 = new SimpleTestPackageContext() { Id = "packageX", Version = "1.0.0", RuntimeJson = runtimeJsonX1 }; var packageX2 = new SimpleTestPackageContext() { Id = "packageX", Version = "2.0.0", RuntimeJson = runtimeJsonX2 }; var packageB = new SimpleTestPackageContext() { Id = "packageB" }; var packageA = new SimpleTestPackageContext() { Id = "packageA" }; var packageX1Runtime = new SimpleTestPackageContext() { Id = "runtime.packageX", Version = "1.0.0" }; var packageX2Runtime = new SimpleTestPackageContext() { Id = "runtime.packageX", Version = "2.0.0" }; packageA.Dependencies.Add(packageX1); packageB.Dependencies.Add(packageX2); packages.Add(packageA); packages.Add(packageB); packages.Add(packageX1); packages.Add(packageX2); packages.Add(packageX1Runtime); packages.Add(packageX2Runtime); await SimpleTestPackageUtility.CreatePackagesAsync(packages, repository); var sources = new List <PackageSource>(); sources.Add(new PackageSource(repository)); var configJson = JObject.Parse(@"{ ""runtimes"": { ""unix"": {} }, ""dependencies"": { ""packageA"": ""1.0.0"", ""packageB"": ""1.0.0"" }, ""frameworks"": { ""_FRAMEWORK_"": {} } }".Replace("_FRAMEWORK_", framework)); var specPath = Path.Combine(projectDir, "TestProject", "project.json"); var spec = JsonPackageSpecReader.GetPackageSpec(configJson.ToString(), "TestProject", specPath).EnsureProjectJsonRestoreMetadata(); var request = new TestRestoreRequest(spec, sources, packagesDir, logger); request.LockFilePath = Path.Combine(projectDir, "project.lock.json"); var command = new RestoreCommand(request); // Act var result = await command.ExecuteAsync(); await result.CommitAsync(logger, CancellationToken.None); var runtimeGraph = result.RestoreGraphs.Single(graph => graph.RuntimeIdentifier == "unix").RuntimeGraph; var selectedRuntimeDependency = runtimeGraph .Runtimes .Single() .Value .RuntimeDependencySets .Single() .Value .Dependencies .Single(); var runtimeDependencyVersion = selectedRuntimeDependency.Value.VersionRange.ToLegacyShortString(); // Assert Assert.True(result.Success); Assert.Equal("x2.app", runtimeGraph.Supports.Single().Key); Assert.Equal("2.0.0", runtimeDependencyVersion); } }
public void RunPublishItemsOutputGroupOutputsTest(bool specifyRid, bool singleFile) { var testProject = new TestProject() { Name = "TestPublishItemsOutputGroupOutputs", TargetFrameworks = "netcoreapp3.0", IsExe = true }; testProject.AdditionalProperties["RuntimeIdentifiers"] = "win-x86"; testProject.AdditionalProperties["RestorePackagesPath"] = @"$(MSBuildProjectDirectory)\..\pkg"; if (specifyRid) { testProject.AdditionalProperties["RuntimeIdentifier"] = "win-x86"; } if (singleFile) { testProject.AdditionalProperties["PublishSingleFile"] = "true"; } var testAsset = _testAssetsManager.CreateTestProject(testProject); var restoreCommand = new RestoreCommand(testAsset); restoreCommand .Execute() .Should() .Pass(); var command = new GetValuesCommand( Log, Path.Combine(testAsset.Path, testProject.Name), testProject.TargetFrameworks, "PublishItemsOutputGroupOutputs", GetValuesCommand.ValueType.Item) { DependsOnTargets = "Publish", MetadataNames = { "OutputPath" }, }; command.Execute().Should().Pass(); var items = from item in command.GetValuesWithMetadata() select new { Identity = item.value, OutputPath = Path.GetFileName(Path.GetFullPath(Path.Combine(testAsset.Path, testProject.Name, item.metadata["OutputPath"]))) }; Log.WriteLine("PublishItemsOutputGroupOutputs contains '{0}' items:", items.Count()); foreach (var item in items) { Log.WriteLine(" '{0}': OutputPath = '{1}'", item.Identity, item.OutputPath); } // Check for the main exe if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { string exeSuffix = specifyRid ? ".exe" : Constants.ExeSuffix; items.Should().ContainSingle(i => i.OutputPath.Equals($"{testProject.Name}{exeSuffix}", StringComparison.OrdinalIgnoreCase)); } // Framework assemblies should be there if we specified and rid and this isn't in the single file case if (specifyRid && !singleFile) { FrameworkAssemblies.ForEach(fa => items.Should().ContainSingle(i => i.OutputPath.Equals(fa, StringComparison.OrdinalIgnoreCase))); items.Should().Contain(i => i.OutputPath.Equals($"{testProject.Name}.deps.json", StringComparison.OrdinalIgnoreCase)); } else { FrameworkAssemblies.ForEach(fa => items.Should().NotContain(i => i.OutputPath.Equals(fa, StringComparison.OrdinalIgnoreCase))); } }
public void RunPublishItemsOutputGroupTest(bool specifyRid, bool singleFile) { var testProject = this.SetupProject(specifyRid, singleFile); var testAsset = _testAssetsManager.CreateTestProject(testProject, identifier: specifyRid.ToString() + singleFile.ToString()); var restoreCommand = new RestoreCommand(testAsset); restoreCommand .Execute() .Should() .Pass(); var command = new GetValuesCommand( Log, Path.Combine(testAsset.Path, testProject.Name), testProject.TargetFrameworks, "PublishItemsOutputGroupOutputs", GetValuesCommand.ValueType.Item) { DependsOnTargets = "PublishItemsOutputGroup", MetadataNames = { "TargetPath", "IsKeyOutput" }, }; command.Execute().Should().Pass(); var items = from item in command.GetValuesWithMetadata() select new { Identity = item.value, TargetPath = item.metadata["TargetPath"], IsKeyOutput = item.metadata["IsKeyOutput"] }; Log.WriteLine("PublishItemsOutputGroup contains '{0}' items:", items.Count()); foreach (var item in items) { Log.WriteLine(" '{0}': TargetPath = '{1}', IsKeyOutput = '{2}'", item.Identity, item.TargetPath, item.IsKeyOutput); } if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { // Check that there's only one key item, and it's the exe string exeSuffix = specifyRid ? ".exe" : Constants.ExeSuffix; items. Where(i => i.IsKeyOutput.Equals("true", StringComparison.OrdinalIgnoreCase)). Should(). ContainSingle(i => i.TargetPath.Equals($"{testProject.Name}{exeSuffix}", StringComparison.OrdinalIgnoreCase)); } // Framework assemblies should be there if we specified and rid and this isn't in the single file case if (specifyRid && !singleFile) { FrameworkAssemblies.ForEach(fa => items.Should().ContainSingle(i => i.TargetPath.Equals(fa, StringComparison.OrdinalIgnoreCase))); } else { FrameworkAssemblies.ForEach(fa => items.Should().NotContain(i => i.TargetPath.Equals(fa, StringComparison.OrdinalIgnoreCase))); } // The deps.json file should be included unless this is the single file case if (!singleFile) { items.Should().ContainSingle(i => i.TargetPath.Equals($"{testProject.Name}.deps.json", StringComparison.OrdinalIgnoreCase)); } }
async Task RestorePackagesAsync( IEnumerable <InteractivePackage> packages, SourceCacheContext cacheContext, CancellationToken cancellationToken) { var restoreContext = new RestoreArgs { CacheContext = cacheContext, Log = Logger, }; // NOTE: This path is typically empty. It could in theory contain nuget.config settings // files, but really we just use it to satisfy nuget API that requires paths, // even when they are never used. var rootPath = packageConfigDirectory; var globalPath = restoreContext.GetEffectiveGlobalPackagesFolder(rootPath, settings); var fallbackPaths = restoreContext.GetEffectiveFallbackPackageFolders(settings); var providerCache = new RestoreCommandProvidersCache(); var restoreProviders = providerCache.GetOrCreate( globalPath, fallbackPaths, SourceRepositories, cacheContext, Logger); // Set up a project spec similar to what you would see in a project.json. // This is sufficient for the dependency graph work done within RestoreCommand. // TODO: XF version pinning during restore? var targetFrameworkInformation = new TargetFrameworkInformation { FrameworkName = TargetFramework, Dependencies = packages.Select(ToLibraryDependency).ToList(), }; var projectSpec = new PackageSpec(new [] { targetFrameworkInformation }) { Name = project.Name, FilePath = rootPath, }; var restoreRequest = new RestoreRequest(projectSpec, restoreProviders, cacheContext, Logger); var restoreCommand = new RestoreCommand(restoreRequest); var result = await restoreCommand.ExecuteAsync(cancellationToken); if (!result.Success) { return; } project.ResetInstallationContext(); // As with installation, restore simply ensures that packages are present in the user's // global package cache. We reference them out of there just like .NET core projects do. // // All resolved packages, including the explicit inputs and their dependencies, are // available as LockFileLibrary instances. foreach (var library in result.LockFile.Libraries) { project.InstallationContext.AddInstalledPackage( GetInteractivePackageFromLibrary(library, project, packages)); } installedPackages = project.InstallationContext.InstalledPackages; UpdateInstalledPackages(); }
public async Task GetInstalledVersion_WithAssetsFile_ChangingPackageSpec_ReturnsVersionsFromAssetsSpecs() { using (var testDirectory = TestDirectory.Create()) { // Setup var projectName = "project1"; var projectFullPath = Path.Combine(testDirectory.Path, projectName + ".csproj"); // Project var projectCache = new ProjectSystemCache(); IVsProjectAdapter projectAdapter = (new Mock <IVsProjectAdapter>()).Object; var project = CreateNetCorePackageReferenceProject(projectName, projectFullPath, projectCache); var projectNames = GetTestProjectNames(projectFullPath, projectName); var packageSpec = GetPackageSpec(projectName, projectFullPath, "[2.0.0, )"); // Restore info var projectRestoreInfo = ProjectJsonTestHelpers.GetDGSpecFromPackageSpecs(packageSpec); projectCache.AddProjectRestoreInfo(projectNames, projectRestoreInfo, new List <IAssetsLogMessage>()); projectCache.AddProject(projectNames, projectAdapter, project).Should().BeTrue(); // Package directories var sources = new List <PackageSource>(); var packagesDir = new DirectoryInfo(Path.Combine(testDirectory, "globalPackages")); var packageSource = new DirectoryInfo(Path.Combine(testDirectory, "packageSource")); packagesDir.Create(); packageSource.Create(); sources.Add(new PackageSource(packageSource.FullName)); var logger = new TestLogger(); var request = new TestRestoreRequest(packageSpec, sources, packagesDir.FullName, logger) { LockFilePath = Path.Combine(testDirectory, "project.assets.json") }; await SimpleTestPackageUtility.CreateFullPackageAsync(packageSource.FullName, "packageA", "2.0.0"); await SimpleTestPackageUtility.CreateFullPackageAsync(packageSource.FullName, "packageA", "3.0.0"); // Act var command = new RestoreCommand(request); var result = await command.ExecuteAsync(); await result.CommitAsync(logger, CancellationToken.None); var packages = await project.GetInstalledPackagesAsync(CancellationToken.None); // Asert Assert.True(result.Success); packages.Should().Contain(a => a.PackageIdentity.Equals(new PackageIdentity("packageA", new NuGetVersion("2.0.0")))); // Setup packageSpec = GetPackageSpec(projectName, projectFullPath, "[3.0.0, )"); // Restore info projectRestoreInfo = ProjectJsonTestHelpers.GetDGSpecFromPackageSpecs(packageSpec); projectCache.AddProjectRestoreInfo(projectNames, projectRestoreInfo, new List <IAssetsLogMessage>()); projectCache.AddProject(projectNames, projectAdapter, project).Should().BeTrue(); request = new TestRestoreRequest(packageSpec, sources, packagesDir.FullName, logger) { LockFilePath = Path.Combine(testDirectory, "project.assets.json") }; // Act command = new RestoreCommand(request); result = await command.ExecuteAsync(); await result.CommitAsync(logger, CancellationToken.None); packages = await project.GetInstalledPackagesAsync(CancellationToken.None); // Asert Assert.True(result.Success); packages.Should().Contain(a => a.PackageIdentity.Equals(new PackageIdentity("packageA", new NuGetVersion("3.0.0")))); } }
public async Task RestoreTargets_RestoreWithRuntimes() { // Arrange var sources = new List <PackageSource>(); var project1Json = @" { ""version"": ""1.0.0"", ""description"": """", ""authors"": [ ""author"" ], ""tags"": [ """" ], ""projectUrl"": """", ""licenseUrl"": """", ""frameworks"": { ""netstandardapp1.5"": { ""dependencies"": { ""packageA"": ""1.0.0"" } } } }"; using (var workingDir = TestDirectory.Create()) { var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages")); var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource")); var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1")); packagesDir.Create(); packageSource.Create(); project1.Create(); sources.Add(new PackageSource(packageSource.FullName)); File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json); var specPath1 = Path.Combine(project1.FullName, "project.json"); var spec1 = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1); var logger = new TestLogger(); var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger); request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json"); request.RequestedRuntimes.Add("win7-x86"); var packageA = new SimpleTestPackageContext() { Id = "packageA" }; packageA.AddFile("lib/netstandard1.5/a.dll"); packageA.AddFile("native/a.dll"); packageA.AddFile("runtimes/unix/native/a.dll"); packageA.AddFile("runtimes/unix/lib/netstandard1.5/a.dll"); packageA.AddFile("runtimes/win7/lib/netstandard1.5/a.dll"); packageA.AddFile("runtimes/win7-x86/lib/netstandard1.5/a.dll"); packageA.AddFile("runtimes/win7-x86/lib/netstandard1.5/en-us/a.resources.dll"); SimpleTestPackageUtility.CreatePackages(packageSource.FullName, packageA); // Act var command = new RestoreCommand(request); var result = await command.ExecuteAsync(); await result.CommitAsync(logger, CancellationToken.None); var format = new LockFileFormat(); var lockFile = format.Read(request.LockFilePath); var targetLib = lockFile.Targets.Single(graph => graph.RuntimeIdentifier == null).Libraries.Single(); var ridTargetLib = lockFile.Targets.Single(graph => graph.RuntimeIdentifier != null).Libraries.Single(); // Assert Assert.True(result.Success); Assert.Equal(5, targetLib.RuntimeTargets.Count); Assert.Equal("runtimes/unix/lib/netstandard1.5/a.dll", targetLib.RuntimeTargets[0].Path); Assert.Equal("runtime", targetLib.RuntimeTargets[0].Properties["assetType"]); Assert.Equal("unix", targetLib.RuntimeTargets[0].Properties["rid"]); Assert.Equal("runtimes/win7-x86/lib/netstandard1.5/en-us/a.resources.dll", targetLib.RuntimeTargets[3].Path); Assert.Equal("resource", targetLib.RuntimeTargets[3].Properties["assetType"]); Assert.Equal("win7-x86", targetLib.RuntimeTargets[3].Properties["rid"]); Assert.Equal("runtimes/unix/native/a.dll", targetLib.RuntimeTargets[1].Path); Assert.Equal("native", targetLib.RuntimeTargets[1].Properties["assetType"]); Assert.Equal("unix", targetLib.RuntimeTargets[1].Properties["rid"]); // This section does not exist for RID graphs Assert.Equal(0, ridTargetLib.RuntimeTargets.Count); } }
public void RunFilesCopiedToPublishDirTest(bool specifyRid, bool singleFile) { var testProject = new TestProject() { Name = "TestFilesCopiedToPublishDir", TargetFrameworks = "netcoreapp3.0", IsSdkProject = true, IsExe = true }; testProject.AdditionalProperties["RuntimeIdentifiers"] = "win-x86"; testProject.AdditionalProperties["RestorePackagesPath"] = @"$(MSBuildProjectDirectory)\..\pkg"; if (specifyRid) { testProject.AdditionalProperties["RuntimeIdentifier"] = "win-x86"; } if (singleFile) { testProject.AdditionalProperties["PublishSingleFile"] = "true"; } var testAsset = _testAssetsManager.CreateTestProject(testProject); var restoreCommand = new RestoreCommand(Log, testAsset.Path, testProject.Name); restoreCommand .Execute() .Should() .Pass(); var command = new GetValuesCommand( Log, Path.Combine(testAsset.Path, testProject.Name), testProject.TargetFrameworks, "FilesCopiedToPublishDir", GetValuesCommand.ValueType.Item) { DependsOnTargets = "ComputeFilesCopiedToPublishDir", MetadataNames = { "RelativePath", "IsKeyOutput" }, }; command.Execute().Should().Pass(); var items = from item in command.GetValuesWithMetadata() select new { Identity = item.value, RelativePath = item.metadata["RelativePath"] }; Log.WriteLine("FilesCopiedToPublishDir contains '{0}' items:", items.Count()); foreach (var item in items) { Log.WriteLine(" '{0}': RelativePath = '{1}'", item.Identity, item.RelativePath); } // Check for the main exe if (RuntimeEnvironment.OperatingSystemPlatform != Platform.Darwin) { string exeSuffix = specifyRid ? ".exe" : Constants.ExeSuffix; items.Should().ContainSingle(i => i.RelativePath.Equals($"{testProject.Name}{exeSuffix}", StringComparison.OrdinalIgnoreCase)); } // Framework assemblies should be there if we specified and rid and this isn't in the single file case if (specifyRid && !singleFile) { FrameworkAssemblies.ForEach(fa => items.Should().ContainSingle(i => i.RelativePath.Equals(fa, StringComparison.OrdinalIgnoreCase))); } else { FrameworkAssemblies.ForEach(fa => items.Should().NotContain(i => i.RelativePath.Equals(fa, StringComparison.OrdinalIgnoreCase))); } // FilesCopiedToPublishDir should never contain the deps.json file items.Should().NotContain(i => i.RelativePath.Equals($"{testProject.Name}.deps.json", StringComparison.OrdinalIgnoreCase)); }
public async Task Project2ProjectInLockFile_PackageReferenceConflict() { // Arrange var sources = new List <PackageSource>() { new PackageSource("https://api.nuget.org/v3/index.json") }; var project1Json = @" { ""version"": ""1.0.0"", ""dependencies"": { }, ""frameworks"": { ""net45"": {} } }"; var project2Json = @" { ""version"": ""1.0.0"", ""dependencies"": { ""Microsoft.VisualBasic"": ""10.0.0"" }, ""frameworks"": { ""net45"": {} } }"; using (var packagesDir = TestDirectory.Create()) using (var workingDir = TestDirectory.Create()) { var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1")); var project2 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project2")); project1.Create(); project2.Create(); File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json); File.WriteAllText(Path.Combine(project2.FullName, "project.json"), project2Json); File.WriteAllText(Path.Combine(project1.FullName, "project1.csproj"), string.Empty); File.WriteAllText(Path.Combine(project2.FullName, "project2.csproj"), string.Empty); var specPath1 = Path.Combine(project1.FullName, "project.json"); var specPath2 = Path.Combine(project2.FullName, "project.json"); var spec1 = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1); var spec2 = JsonPackageSpecReader.GetPackageSpec(project2Json, "project2", specPath2); var logger = new TestLogger(); var request = new TestRestoreRequest(spec1, sources, packagesDir, logger); request.ExternalProjects.Add(new ExternalProjectReference( "project1", spec1, Path.Combine(project1.FullName, "project1.csproj"), new string[] { "project2" })); request.ExternalProjects.Add(new ExternalProjectReference( "project2", spec2, Path.Combine(project2.FullName, "project2.csproj"), new string[] { })); request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json"); var format = new LockFileFormat(); // Act var command = new RestoreCommand(request); var result = await command.ExecuteAsync(); await result.CommitAsync(logger, CancellationToken.None); // Assert Assert.True(result.Success, logger.ShowMessages()); } }
public async Task Project2ProjectInLockFile_VerifyProjectsReferencesInLibAndTargets() { // Arrange var sources = new List <PackageSource>(); var project1Json = @" { ""version"": ""1.0.0"", ""frameworks"": { ""net45"": {} } }"; var project2Json = @" { ""version"": ""1.0.0"", ""frameworks"": { ""net45"": {} } }"; var project3Json = @" { ""version"": ""1.0.0"", ""dependencies"": { }, ""frameworks"": { ""net45"": {} } }"; using (var packagesDir = TestDirectory.Create()) using (var workingDir = TestDirectory.Create()) { var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1")); var project2 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project2")); var project3 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project3")); project1.Create(); project2.Create(); project3.Create(); File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json); File.WriteAllText(Path.Combine(project2.FullName, "project.json"), project2Json); File.WriteAllText(Path.Combine(project3.FullName, "project.json"), project3Json); var project1Path = Path.Combine(project1.FullName, "project1.csproj"); var project2Path = Path.Combine(project2.FullName, "project2.csproj"); var project3Path = Path.Combine(project3.FullName, "project3.csproj"); File.WriteAllText(project1Path, string.Empty); File.WriteAllText(project2Path, string.Empty); File.WriteAllText(project3Path, string.Empty); var specPath1 = Path.Combine(project1.FullName, "project.json"); var specPath2 = Path.Combine(project2.FullName, "project.json"); var specPath3 = Path.Combine(project3.FullName, "project.json"); var spec1 = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1); var spec2 = JsonPackageSpecReader.GetPackageSpec(project1Json, "project2", specPath2); var spec3 = JsonPackageSpecReader.GetPackageSpec(project1Json, "project3", specPath3); var logger = new TestLogger(); var restoreContext = new RestoreArgs() { GlobalPackagesFolder = packagesDir, Log = logger, CacheContext = new SourceCacheContext() }; // Modify specs for netcore spec3 = spec3.WithTestRestoreMetadata(); spec3.FilePath = project3Path; spec3.RestoreMetadata.ProjectPath = project3Path; spec3.RestoreMetadata.ProjectUniqueName = project3Path; spec2 = spec2.WithTestRestoreMetadata().WithTestProjectReference(spec3); spec2.FilePath = project2Path; spec2.RestoreMetadata.ProjectPath = project2Path; spec2.RestoreMetadata.ProjectUniqueName = project2Path; spec1 = spec1.WithTestRestoreMetadata().WithTestProjectReference(spec2); spec1.FilePath = project1Path; spec1.RestoreMetadata.ProjectPath = project1Path; spec1.RestoreMetadata.ProjectUniqueName = project1Path; var request = await ProjectJsonTestHelpers.GetRequestAsync(restoreContext, spec1, spec2, spec3); request.LockFilePath = Path.Combine(project1.FullName, "project.assets.json"); var format = new LockFileFormat(); // Act var command = new RestoreCommand(request); var result = await command.ExecuteAsync(); await result.CommitAsync(logger, CancellationToken.None); Assert.True(result.Success, logger.ShowMessages()); var lockFile = format.Read(request.LockFilePath, logger); var project1Lib = lockFile.GetLibrary("project1", NuGetVersion.Parse("1.0.0")); var project2Lib = lockFile.GetLibrary("project2", NuGetVersion.Parse("1.0.0")); var project3Lib = lockFile.GetLibrary("project3", NuGetVersion.Parse("1.0.0")); var project2Target = lockFile.GetTarget(FrameworkConstants.CommonFrameworks.Net45, runtimeIdentifier: null) .Libraries .Where(lib => lib.Name == "project2") .Single(); var project3Target = lockFile.GetTarget(FrameworkConstants.CommonFrameworks.Net45, runtimeIdentifier: null) .Libraries .Where(lib => lib.Name == "project3") .Single(); // Assert Assert.True(result.Success); Assert.Equal(2, lockFile.Libraries.Count); Assert.Equal("project", project2Lib.Type); Assert.Equal("project", project3Lib.Type); Assert.Equal("../project2/project2.csproj", project2Lib.Path); Assert.Equal("../project3/project3.csproj", project3Lib.Path); Assert.Equal("../project2/project2.csproj", project2Lib.MSBuildProject); Assert.Equal("../project3/project3.csproj", project3Lib.MSBuildProject); Assert.Equal(1, project2Target.Dependencies.Count); Assert.Equal("project3", project2Target.Dependencies.Single().Id); Assert.Equal("1.0.0", project2Target.Dependencies.Single().VersionRange.ToLegacyShortString()); Assert.Equal(0, project3Target.Dependencies.Count); Assert.Equal(".NETFramework,Version=v4.5", project2Target.Framework); Assert.Equal(".NETFramework,Version=v4.5", project3Target.Framework); } }
public async Task Project2ProjectInLockFile_VerifyP2PWithNonProjectJsonReference() { // Arrange var sources = new List <PackageSource>(); var projectJson = @" { ""version"": ""1.0.0"", ""dependencies"": { }, ""frameworks"": { ""net45"": {} } }"; using (var packagesDir = TestDirectory.Create()) using (var workingDir = TestDirectory.Create()) { var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1")); var project2 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project2")); var project3 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project3")); project1.Create(); project2.Create(); project3.Create(); File.WriteAllText(Path.Combine(project1.FullName, "project.json"), projectJson); File.WriteAllText(Path.Combine(project1.FullName, "project1.csproj"), string.Empty); File.WriteAllText(Path.Combine(project2.FullName, "project2.csproj"), string.Empty); File.WriteAllText(Path.Combine(project3.FullName, "project3.csproj"), string.Empty); var specPath1 = Path.Combine(project1.FullName, "project.json"); var spec1 = JsonPackageSpecReader.GetPackageSpec(projectJson, "project1", specPath1); var logger = new TestLogger(); var request = new TestRestoreRequest(spec1, sources, packagesDir, logger); request.ExternalProjects.Add(new ExternalProjectReference( "project1", spec1, Path.Combine(project1.FullName, "project1.xproj"), new string[] { "project2" })); request.ExternalProjects.Add(new ExternalProjectReference( "project2", null, Path.Combine(project2.FullName, "project2.csproj"), new string[] { "project3" })); request.ExternalProjects.Add(new ExternalProjectReference( "project3", null, Path.Combine(project3.FullName, "project3.csproj"), new string[] { })); request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json"); var format = new LockFileFormat(); // Act var command = new RestoreCommand(request); var result = await command.ExecuteAsync(); await result.CommitAsync(logger, CancellationToken.None); var lockFile = format.Read(request.LockFilePath, logger); var project1Lib = lockFile.GetLibrary("project1", NuGetVersion.Parse("1.0.0")); var project2Lib = lockFile.GetLibrary("project2", NuGetVersion.Parse("1.0.0")); var project3Lib = lockFile.GetLibrary("project3", NuGetVersion.Parse("1.0.0")); var project2Target = lockFile.GetTarget(FrameworkConstants.CommonFrameworks.Net45, runtimeIdentifier: null) .Libraries .Where(lib => lib.Name == "project2") .Single(); var project3Target = lockFile.GetTarget(FrameworkConstants.CommonFrameworks.Net45, runtimeIdentifier: null) .Libraries .Where(lib => lib.Name == "project3") .Single(); // Assert Assert.True(result.Success); Assert.Equal(2, lockFile.Libraries.Count); Assert.Equal("project", project2Lib.Type); Assert.Equal("project", project3Lib.Type); Assert.Null(project2Lib.Path); Assert.Null(project3Lib.Path); Assert.Equal("../project2/project2.csproj", project2Lib.MSBuildProject); Assert.Equal("../project3/project3.csproj", project3Lib.MSBuildProject); Assert.Equal(1, project2Target.Dependencies.Count); Assert.Equal("project3", project2Target.Dependencies.Single().Id); Assert.Equal("1.0.0", project2Target.Dependencies.Single().VersionRange.ToLegacyShortString()); Assert.Equal(0, project3Target.Dependencies.Count); Assert.Null(project2Target.Framework); Assert.Null(project3Target.Framework); } }
private async Task<bool> Restore(PublishRoot root, PublishProject publishProject, string restoreDirectory, IEnumerable<FrameworkName> targetFrameworks) { var appEnv = PlatformServices.Default.Application; var feedOptions = new FeedOptions(); feedOptions.IgnoreFailedSources = true; feedOptions.Sources.Add(root.TargetPackagesPath); feedOptions.TargetPackagesFolder = root.TargetPackagesPath; var restoreCommand = new RestoreCommand(appEnv); restoreCommand.TargetFrameworks.AddRange(targetFrameworks); restoreCommand.RequestedRuntimes = root.RuntimeIdentifiers; restoreCommand.SkipRestoreEvents = true; restoreCommand.SkipInstall = true; // This is a workaround for #1322. Since we use restore to generate the lock file // after publish, it's possible to fail restore after copying the closure // if framework assemblies and packages have the same name. This is more likely now // since dependencies may exist in the top level restoreCommand.IgnoreMissingDependencies = true; restoreCommand.CheckHashFile = false; restoreCommand.RestoreDirectories.Add(restoreDirectory); restoreCommand.FeedOptions = feedOptions; // Mute "dnu restore" subcommand restoreCommand.Reports = Reports.Constants.NullReports; var success = await restoreCommand.Execute(); return success; }