public async Task RestoreRunnerEx_WithExistingPackage_DoesNotCreateAnyAssetsAsync() { using (var pathContext = new SimpleTestPathContext()) using (var context = new SourceCacheContext()) { // Arrange var packageId = "x"; var packageVersion = "1.0.0"; var logger = new TestLogger(); var library = new LibraryIdentity(packageId, NuGetVersion.Parse(packageVersion), LibraryType.Reference); var package = new SimpleTestPackageContext(packageId, packageVersion); await SimpleTestPackageUtility.CreateFolderFeedV3Async( pathContext.PackageSource, PackageSaveMode.Defaultv3, package); // Act var results = await RestoreRunnerEx.RunWithoutCommit(library, Settings.LoadDefaultSettings(pathContext.SolutionRoot), logger); // Assert results.Count.Should().Be(1); RestoreResult restoreResult = results.Single().Result; restoreResult.Success.Should().BeTrue(); File.Exists(restoreResult.LockFilePath).Should().BeFalse(); File.Exists(Path.GetDirectoryName(restoreResult.LockFilePath)).Should().BeFalse(); } }
public static SdkResult GetSdkResult(SdkReference sdk, object nuGetVersion, SdkResolverContext context, SdkResultFactory factory) { // Cast the NuGet version since the caller does not want to consume NuGet classes directly var parsedSdkVersion = (NuGetVersion)nuGetVersion; // Stores errors and warnings for the result ICollection <string> errors = new List <string>(); ICollection <string> warnings = new List <string>(); // Load NuGet settings and a path resolver var settings = Settings.LoadDefaultSettings(context.ProjectFilePath); var fallbackPackagePathResolver = new FallbackPackagePathResolver(NuGetPathContext.Create(settings)); // Attempt to find a package if its already installed if (!TryGetMSBuildSdkPackageInfo(fallbackPackagePathResolver, sdk.Name, parsedSdkVersion, out var installedPath, out var installedVersion)) { try { // Asynchronously run the restore without a commit which find the package on configured feeds, download, and unzip it without generating any other files var results = RestoreRunnerEx.RunWithoutCommit( context.ProjectFilePath, sdk.Name, parsedSdkVersion.ToFullString(), settings, new NuGetSdkLogger(context.Logger, warnings, errors)) .ConfigureAwait(continueOnCapturedContext: false) .GetAwaiter() .GetResult(); fallbackPackagePathResolver = new FallbackPackagePathResolver(NuGetPathContext.Create(settings)); // Look for a successful result, any errors are logged by NuGet foreach (var result in results.Select(i => i.Result).Where(i => i.Success)) { // Find the information about the package that was installed. In some cases, the version can be different than what was specified (like you specify 1.0 but get 1.0.0) var installedPackage = result.GetAllInstalled().FirstOrDefault(i => i.Name.Equals(sdk.Name)); if (installedPackage != null) { if (!TryGetMSBuildSdkPackageInfo(fallbackPackagePathResolver, installedPackage.Name, installedPackage.Version, out installedPath, out installedVersion)) { // This should never happen because we were told the package was successfully installed. // If we can't find it, we probably did something wrong with the NuGet API errors.Add(string.Format(CultureInfo.CurrentCulture, Strings.CouldNotFindInstalledPackage, sdk)); } } else { // This should never happen because we were told the restore succeeded. // If we can't find the package from GetAllInstalled(), we probably did something wrong with the NuGet API errors.Add(string.Format(CultureInfo.CurrentCulture, Strings.PackageWasNotInstalled, sdk, sdk.Name)); } } } catch (Exception e) { errors.Add(e.Message); } } if (errors.Count == 0) { return(factory.IndicateSuccess(path: installedPath, version: installedVersion, warnings: warnings)); } return(factory.IndicateFailure(errors, warnings)); }
public static SdkResult GetSdkResult(SdkReference sdk, object nuGetVersion, SdkResolverContext context, SdkResultFactory factory) { // Cast the NuGet version since the caller does not want to consume NuGet classes directly var parsedSdkVersion = (NuGetVersion)nuGetVersion; // Stores errors and warnings for the result ICollection <string> errors = new List <string>(); ICollection <string> warnings = new List <string>(); // Load NuGet settings and a path resolver var settings = Settings.LoadDefaultSettings(context.ProjectFilePath); var fallbackPackagePathResolver = new FallbackPackagePathResolver(NuGetPathContext.Create(settings)); var libraryIdentity = new LibraryIdentity(sdk.Name, parsedSdkVersion, LibraryType.Package); // Attempt to find a package if its already installed if (!TryGetMSBuildSdkPackageInfo(fallbackPackagePathResolver, libraryIdentity, out var installedPath, out var installedVersion)) { try { var nugetSDKLogger = new NuGetSdkLogger(context.Logger, warnings, errors); DefaultCredentialServiceUtility.SetupDefaultCredentialService(nugetSDKLogger, nonInteractive: context.IsNonInteractive()); // Asynchronously run the restore without a commit which find the package on configured feeds, download, and unzip it without generating any other files // This must be run in its own task because legacy project system evaluates projects on the UI thread which can cause RunWithoutCommit() to deadlock // https://developercommunity.visualstudio.com/content/problem/311379/solution-load-never-completes-when-project-contain.html var restoreTask = Task.Run(() => RestoreRunnerEx.RunWithoutCommit( libraryIdentity, settings, nugetSDKLogger)); var results = restoreTask.Result; fallbackPackagePathResolver = new FallbackPackagePathResolver(NuGetPathContext.Create(settings)); // Look for a successful result, any errors are logged by NuGet foreach (var result in results.Select(i => i.Result).Where(i => i.Success)) { // Find the information about the package that was installed. In some cases, the version can be different than what was specified (like you specify 1.0 but get 1.0.0) var installedPackage = result.GetAllInstalled().FirstOrDefault(i => i == libraryIdentity); if (installedPackage != null) { if (TryGetMSBuildSdkPackageInfo(fallbackPackagePathResolver, installedPackage, out installedPath, out installedVersion)) { break; } // This should never happen because we were told the package was successfully installed. // If we can't find it, we probably did something wrong with the NuGet API errors.Add(string.Format(CultureInfo.CurrentCulture, Strings.CouldNotFindInstalledPackage, sdk)); } else { // This should never happen because we were told the restore succeeded. // If we can't find the package from GetAllInstalled(), we probably did something wrong with the NuGet API errors.Add(string.Format(CultureInfo.CurrentCulture, Strings.PackageWasNotInstalled, sdk, sdk.Name)); } } } catch (Exception e) { errors.Add(e.Message); } finally { // The CredentialService lifetime is for the duration of the process. We should not leave a potentially unavailable logger. DefaultCredentialServiceUtility.UpdateCredentialServiceDelegatingLogger(NullLogger.Instance); } } if (errors.Count == 0) { return(factory.IndicateSuccess(path: installedPath, version: installedVersion, warnings: warnings)); } return(factory.IndicateFailure(errors, warnings)); }
private async Task <int> OnExecuteAsync() { var reporter = new ConsoleReporter(PhysicalConsole.Singleton) { IsVerbose = Verbose }; var installDir = string.IsNullOrEmpty(OutputDirectory) ? Path.Combine(Directory.GetCurrentDirectory(), "packages") : Path.GetFullPath(OutputDirectory); var tempFilePath = Path.Combine(AppContext.BaseDirectory, "projectThatNeverExists.csproj"); ISettings settings = Settings.LoadDefaultSettings(tempFilePath); VersionRange versionRange; if (!string.IsNullOrEmpty(Version)) { if (!VersionRange.TryParse(Version, out versionRange)) { reporter.Error($"Invalid nuget version '{Version}'"); return(1); } } else { versionRange = Prerelease ? VersionRange.AllFloating : VersionRange.AllStableFloating; } var logger = new ConsoleNuGetLogger(reporter); var results = await RestoreRunnerEx.RunWithoutCommit(tempFilePath, installDir, PackageId, versionRange, settings, Sources, logger); var success = false; foreach (var result in results) { if (result.Result.Success) { var installedVersion = result.Result.LockFile.Libraries.FirstOrDefault(l => string.Equals(PackageId, l.Name, StringComparison.OrdinalIgnoreCase)); if (installedVersion != null) { var path = installedVersion.Path; reporter.Output($"Installed {installedVersion.Name} {installedVersion.Version}"); foreach (var file in installedVersion.Files) { reporter.Verbose("Package file: " + file); } success = true; break; } } else { foreach (var unresolved in result.Result.GetAllUnresolved()) { reporter.Warn($"Could not find a package {unresolved.Name} in the version range {unresolved.VersionRange}"); } } } if (success) { reporter.Output("Installation succeeded"); return(0); } reporter.Error("Installation failed"); return(success ? 1 : 0); }