private static ImmutableArray<PackageReference> InitializeAssemblyRegistry(FunctionMetadata metadata) { var builder = ImmutableArray<PackageReference>.Empty.ToBuilder(); string fileName = Path.Combine(Path.GetDirectoryName(metadata.Source), CSharpConstants.ProjectLockFileName); if (File.Exists(fileName)) { var jobject = JObject.Parse(File.ReadAllText(fileName)); var target = jobject.SelectTokens(string.Format(CultureInfo.InvariantCulture, "$.targets['{0}']", FrameworkTargetName)).FirstOrDefault(); if (target != null) { string nugetHome = PackageManager.GetNugetPackagesPath(); foreach (JProperty token in target) { var referenceNameParts = token.Name.Split('/'); if (referenceNameParts.Length != 2) { throw new FormatException(string.Format(CultureInfo.InvariantCulture, "The package name '{0}' is not correctly formatted.", token.Name)); } var package = new PackageReference(referenceNameParts[0], referenceNameParts[1]); var references = token.SelectTokens("$..compile").FirstOrDefault(); if (references != null) { foreach (JProperty reference in references) { if (!reference.Name.EndsWith(EmptyFolderFileMarker, StringComparison.Ordinal)) { string path = Path.Combine(nugetHome, token.Name, reference.Name); path = path.Replace('/', '\\'); if (File.Exists(path)) { package.Assemblies.Add(AssemblyName.GetAssemblyName(path), path); } } } } var frameworkAssemblies = token.SelectTokens("$..frameworkAssemblies").FirstOrDefault(); if (frameworkAssemblies != null) { foreach (var assembly in frameworkAssemblies) { string assemblyName = assembly.ToString(); package.FrameworkAssemblies.Add(new AssemblyName(assemblyName), assemblyName); } } builder.Add(package); } } } return builder.ToImmutableArray(); }
public override void ExecuteCommand() { if (string.IsNullOrEmpty(Directory)) { Directory = Environment.CurrentDirectory; } if (_repository == null) { _repository = AggregateRepositoryHelper.CreateAggregateRepositoryFromSources(RepositoryFactory, SourceProvider, Source); } var packageFiles = _fileSystem.GetFiles(Directory, "packages.config", true).ToList(); Console.WriteLine("Processing : {0} files.",packageFiles.Count); Parallel.ForEach(packageFiles, packageFile => { Console.WriteLine("\t{0}", packageFile); var newReferences = new List<PackageReference>(); var packageFileDetails = new PackageReferenceFile(_fileSystem, packageFile); foreach (var packageReference in packageFileDetails.GetPackageReferences()) { Console.WriteLine("\t\t{0}",packageReference.ToString()); var exists = _repository.FindPackage(packageReference.Id, packageReference.Version); if (exists != null) { Console.WriteLine("\t\t\tExists, not changing."); newReferences.Add(packageReference); } else { var package = _repository.FindPackagesById(packageReference.Id).FirstOrDefault(); if (package == null) { Console.WriteLine("\t\t\tNot found, no change."); newReferences.Add(packageReference); } else { var newReference = new PackageReference(package.Id, package.Version, new VersionSpec(), new FrameworkName(".NET Framework, Version=4.0"), false); Console.WriteLine("\t\t\tUpdated to {0}", newReference.ToString()); newReferences.Add(newReference); } } } //TODO Clear the file (must be an easier way). Console.WriteLine("Clearing existing file..."); foreach (var packageReference in packageFileDetails.GetPackageReferences()) { packageFileDetails.DeleteEntry(packageReference.Id, packageReference.Version); } //Add the new references. Console.WriteLine("Adding new references..."); foreach (var packageReference in newReferences) { packageFileDetails.AddEntry(packageReference.Id, packageReference.Version); } }); }
[TestCase("Assembly.Common", "0.0", "[1.0,2.0]", false, Result = "0.0")] // get latest constrained version (0.0 version) public string FindPackageLatestTests(string id, string version, string versionSpec, bool latest) { var pr = new PackageReference(id, SemanticVersion.Parse(version), string.IsNullOrEmpty(versionSpec) ? new VersionSpec() : VersionUtility.ParseVersionSpec(versionSpec), new FrameworkName(".NET Framework, Version=4.0"), false); var prc = new PackageResolutionManager(new Mock<ILogger>().Object, latest, new MemoryBasedPackageCache(new Mock<ILogger>().Object)); var v = prc.ResolveInstallableVersion(Utilities.GetFactory().CreateRepository("SingleAggregate"), pr); return v != null ? v.ToString() : ""; }
private void CreateMarker(IVsTextLines buffer, PackageReference packageReference) { var marker = new PackageReferenceMarker(_taskProvider, packageReference); marker.MarkerInvalidated += Marker_MarkerInvalidated; marker.BeforeBufferClose += Marker_BeforeBufferClose; marker.CreateTextLineMarker(buffer); _markers.Add(marker); }
public static InstalledPackageReference SafeToInstalledPackageReference(PackageReference packageRef) { if (packageRef == null) { return null; } return new InstalledPackageReference( CoreConverters.SafeToPackageIdentity(packageRef.Id, packageRef.Version), CoreConverters.SafeToVerRange(packageRef.VersionConstraint), packageRef.TargetFramework, packageRef.IsDevelopmentDependency, packageRef.RequireReinstallation); }
public void PackagesConfigWriter_OpenExistingFile() { // Arrange using (var folderPath = TestDirectory.Create()) { var filePath = Path.Combine(folderPath, "packages.config"); using (var fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write)) { using (var fileWriter = new StreamWriter(fileStream)) { var content = @"<?xml version=""1.0"" encoding=""utf-8""?> <packages> <package id = ""packageA"" version = ""1.0.0"" targetFramework = ""win81"" userInstalled = ""true"" protocolVersion = ""V2"" /> <package id = ""Microsoft.ApplicationInsights.PersistenceChannel"" version = ""0.14.3-build00177"" targetFramework = ""win81"" /> <package id = ""Microsoft.ApplicationInsights.WindowsApps"" version = ""0.14.3-build00177"" targetFramework = ""win81"" /> <package id = ""Microsoft.Diagnostics.Tracing.EventSource.Redist"" version = ""1.1.16-beta"" targetFramework = ""win81"" /> <package id = ""System.Numerics.Vectors"" version = ""4.0.0"" targetFramework = ""win81"" /> </packages>"; fileWriter.Write(content); } } var stream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite); using (var writer = new PackagesConfigWriter(stream, false)) { // Act var packageIdentityA1 = new PackageIdentity("packageA", NuGetVersion.Parse("1.0.0")); var packageReferenceA1 = new PackageReference(packageIdentityA1, NuGetFramework.Parse("win81"), userInstalled: true, developmentDependency: false, requireReinstallation: false); var packageIdentityA2 = new PackageIdentity("packageA", NuGetVersion.Parse("1.0.1")); var packageReferenceA2 = new PackageReference(packageIdentityA2, NuGetFramework.Parse("net45")); writer.UpdatePackageEntry(packageReferenceA1, packageReferenceA2); } // Assert stream.Seek(0, SeekOrigin.Begin); var xml = XDocument.Load(stream); // Assert Assert.Equal("utf-8", xml.Declaration.Encoding); var packageNode = xml.Descendants(PackagesConfig.PackageNodeName).FirstOrDefault(); Assert.Equal(packageNode.ToString(), "<package id=\"packageA\" version=\"1.0.1\" targetFramework=\"net45\" userInstalled=\"true\" protocolVersion=\"V2\" />"); } }
public void ParsesVersionAndSpecialVersion( string version, string expectedVersion, string expectedSpecialVersion) { // Arrange, Act var packageReference = new PackageReference( "packageId", new FrameworkName(".NETFramework,Version=v4.0"), version); // Assert packageReference.Version.ShouldEqual(string.IsNullOrWhiteSpace(expectedVersion) ? new Version() : new Version(expectedVersion)); packageReference.SpecialVersion.ShouldEqual(expectedSpecialVersion); }
public void PackageReferenceMergeComparer_AnyNullArgument_ReturnsExpectedResult() { // Arrange PackageReference testPkgReference = CreatePackageReference("Abc", "1.0", "net6.0"); // Act and Assert 1: Second is null int result1 = GetPackageReferenceUtility.PackageReferenceMergeComparer.Compare(testPkgReference, null); Assert.True(result1 > 0); // Act and Assert 2: First is null int result2 = GetPackageReferenceUtility.PackageReferenceMergeComparer.Compare(null, testPkgReference); Assert.True(result2 < 0); // Act and Assert 3: Both are null int result3 = GetPackageReferenceUtility.PackageReferenceMergeComparer.Compare(null, null); Assert.True(result3 == 0); var prWithNullIdentity = new PackageReference(null, null); // Act and Assert 4: Second with null PackageIdentity int result4 = GetPackageReferenceUtility.PackageReferenceMergeComparer.Compare(testPkgReference, prWithNullIdentity); Assert.True(result4 > 0); // Act and Assert 5: First with null PackageIdentity int result5 = GetPackageReferenceUtility.PackageReferenceMergeComparer.Compare(prWithNullIdentity, testPkgReference); Assert.True(result5 < 0); // Act and Assert 6: First with null PackageIdentity and null int result6 = GetPackageReferenceUtility.PackageReferenceMergeComparer.Compare(prWithNullIdentity, null); Assert.Equal(0, result6); PackageReference pkgRefWithNullVersion1 = CreatePackageReference("nullVersion", null, framework: null); PackageReference pkgRefWithNullVersion2 = CreatePackageReference("otherVersion", null, framework: null); // Act and Assert 7: First Null PackageIdentity and Second with null version, compare only with package IDs int result7 = GetPackageReferenceUtility.PackageReferenceMergeComparer.Compare(prWithNullIdentity, pkgRefWithNullVersion1); Assert.True(result7 < 0); // Act and Assert 8: Only package ID's on both int result8 = GetPackageReferenceUtility.PackageReferenceMergeComparer.Compare(pkgRefWithNullVersion1, pkgRefWithNullVersion2); Assert.True(result8 < 0); }
/// <summary> /// Returns the files installed by the given package. /// </summary> /// <param name="package">The package.</param> /// <param name="type">The package type.</param> /// <param name="isGlobal">Whether the package is globally installed.</param> /// <returns>The files installed by the given package.</returns> public IReadOnlyCollection <IFile> GetFiles(PackageReference package, PackageType type, bool isGlobal) { if (type == PackageType.Addin) { throw new InvalidOperationException("NPM Module does not support Addins'"); } if (type == PackageType.Tool) { return(GetToolFiles(package, isGlobal)); } throw new InvalidOperationException("Unknown resource type."); }
public void AddPackageReference(string id, string version, VersionRange versionRange = null) { var packageId = new PackageIdentity(id, new NuGetVersion(version)); var packageReference = new PackageReference( packageId, new NuGetFramework("net45"), true, false, false, versionRange ); InstalledPackages.Add(packageReference); }
static bool IsMatch(PackageReference package, string packageId, NuGetVersion version = null) { if (!StringComparer.OrdinalIgnoreCase.Equals(package.PackageIdentity.Id, packageId)) { return(false); } if (version != null) { return(package.PackageIdentity.Version == version); } return(true); }
private ModulesInstallationLocation GetModuleInstallationLocation(PackageReference package) { if (package.GetSwitch("global")) { return(ModulesInstallationLocation.Global); } if (package.GetSwitch("caketools")) { return(ModulesInstallationLocation.Tools); } return(ModulesInstallationLocation.Workdir); }
private ProcessArgumentBuilder GetArguments( PackageReference definition, ICakeConfiguration config) { var arguments = new ProcessArgumentBuilder(); arguments.Append("install"); arguments.Append("-y"); var packageString = new StringBuilder(definition.Package); // if an absolute uri is specified for source, use this // otherwise check config for customise package source/s if (definition.Address != null) { arguments.Append($"--repofrompath=\"{definition.Package},{definition.Address.AbsoluteUri}\""); arguments.Append($"--repo={definition.Package}"); } else { var dnfSource = config.GetValue("DNF_Source"); if (!string.IsNullOrWhiteSpace(dnfSource)) { arguments.Append($"--repofrompath=\"{definition.Package},{dnfSource}\""); arguments.Append($"--repo={definition.Package}"); } } if (_log.Verbosity == Verbosity.Verbose || _log.Verbosity == Verbosity.Diagnostic) { arguments.Append("--verbose"); } if (definition.GetSwitch("best")) { arguments.Append("--best"); } // Version if (definition.Parameters.ContainsKey("version")) { packageString.Append($"-{definition.Parameters["version"].First()}"); } if (definition.Parameters.ContainsKey("arch")) { packageString.Append($".{definition.Parameters["arch"].First()}"); } arguments.Append(packageString.ToString()); return(arguments); }
/// <summary> /// Determines whether the specified <paramref name="compilation"/> references the provided <paramref name="package"/>. /// </summary> /// <param name="compilation"><see cref="Compilation"/> to check if contains a reference to the provided <paramref name="package"/>.</param> /// <param name="package"><see cref="PackageReference"/> of Durian package to check for.</param> /// <exception cref="ArgumentNullException"><paramref name="package"/> is <see langword="null"/>. -or- <paramref name="compilation"/> is <see langword="null"/>.</exception> public static bool HasReference(this Compilation compilation, PackageReference package) { if (compilation is null) { throw new ArgumentNullException(nameof(compilation)); } if (package is null) { throw new ArgumentNullException(nameof(package)); } return(HasReference_Internal(compilation, package.EnumValue)); }
public static PackageReferenceContextInfo Create(PackageReference packageReference) { Assumes.NotNull(packageReference); var packageReferenceContextInfo = new PackageReferenceContextInfo(packageReference.PackageIdentity, packageReference.TargetFramework) { IsAutoReferenced = (packageReference as BuildIntegratedPackageReference)?.Dependency?.AutoReferenced == true, AllowedVersions = packageReference.AllowedVersions, IsUserInstalled = packageReference.IsUserInstalled, IsDevelopmentDependency = packageReference.IsDevelopmentDependency }; return(packageReferenceContextInfo); }
public static bool ShouldLoadDependencies(this PackageReference packageReference, ICakeConfiguration config) { bool loadDependencies; if (packageReference.Parameters.ContainsKey(LoadDependenciesKey)) { bool.TryParse(packageReference.Parameters[LoadDependenciesKey].FirstOrDefault() ?? bool.TrueString, out loadDependencies); } else { bool.TryParse(config.GetValue(Constants.NuGet.LoadDependencies) ?? bool.FalseString, out loadDependencies); } return(loadDependencies); }
public void IsRestored_OnePackageLookupPathForPackageReference_ReturnTrue() { CreateSolution(@"d:\projects\myproject\myproject.sln"); CreateRepository(solution); PackageReference packageReference = CreatePackageReference("MyPackage", "1.2.3.4"); AddFileToLocalRepositoryLookupPath( packageReference, @"d:\projects\myproject\packages\MyPackage.1.2.3.4\MyPackage.1.2.3.4.nupkg"); bool restored = repository.IsRestored(packageReference); Assert.IsTrue(restored); }
public IReadOnlyCollection <IFile> GetFiles(PackageReference package, PackageType type) { if (type == PackageType.Addin) { throw new InvalidOperationException("DNF Module does not support addins"); } if (type == PackageType.Tool) { return(GetToolFiles(package)); } throw new InvalidOperationException("Unknown package type."); }
protected NuGetContentResolverFixture(string framework, Runtime runtime) { Environment = FakeEnvironment.CreateUnixEnvironment(); Environment.Runtime.BuiltFramework = new FrameworkName(framework); Environment.Runtime.Runtime = runtime; FileSystem = new FakeFileSystem(Environment); Globber = new Globber(FileSystem, Environment); Log = new FakeLog(); Path = "/Working"; PackageType = PackageType.Addin; Package = new PackageReference("nuget:?package=Foo"); }
public PackageReference AddPackageReference(string packageId, string packageVersion) { var packageReference = new PackageReference( packageId, new SemanticVersion(packageVersion), null, null, false, false); PackageReferences.Add(packageReference); return(packageReference); }
void Run(string packageId, string packageVersion) { var packageReference = new PackageReference( packageId, new SemanticVersion(packageVersion), null, null, false); var parentNode = new TestableProjectPackagesFolderNode(project.FakeDotNetProject, null); var node = new PackageReferenceNode(parentNode, packageReference, true); reinstaller.Run(node); }
private DirectoryPath GetToolsLocalInstallPath(PackageReference package) { var toolsFolder = _fileSystem.GetDirectory( _configuration.GetToolPath(_environment.WorkingDirectory, _environment)); if (!toolsFolder.Exists) { toolsFolder.Create(); } var modules = toolsFolder.Path.Combine("./node_modules/"); return(GetPackagePath(modules, package)); }
/// <summary> /// Build up the recipe file location from the package reference /// </summary> public static Path GetPackageRecipeFile( Path workingDirectory, PackageReference package) { if (package.IsLocal) { var recipeFile = workingDirectory + package.Path; return(recipeFile); } else { throw new InvalidOperationException("Non-local packages not supported."); } }
/// <summary> /// Get the package reference path /// </summary> public static Path GetPackageReferencePath( Path workingDirectory, PackageReference reference) { // If the path is relative then combine with the working directory var packagePath = reference.Path; if (!packagePath.HasRoot) { packagePath = workingDirectory + packagePath; } return(packagePath); }
public void Should_Use_Feed_Specified_In_NuGet_Config_If_Available() { var feed = "https://foo.bar/api.json"; var package = new PackageReference($"nuget:{feed}?package=First.Package"); var settings = Substitute.For <ISettings>(); var packageSourceSection = Activator.CreateInstance( type: typeof(VirtualSettingSection), bindingAttr: System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance, binder: null, args: new object[] { ConfigurationConstants.PackageSources, (IReadOnlyDictionary <string, string>)null, new[] { new SourceItem("foobar", feed) } }, culture: null); var credentialSection = Activator.CreateInstance( type: typeof(VirtualSettingSection), bindingAttr: System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance, binder: null, args: new object[] { ConfigurationConstants.CredentialsSectionName, (IReadOnlyDictionary <string, string>)null, new[] { new CredentialsItem("foobar", "*****@*****.**", "p455w0rdz", true) } }, culture: null); settings.GetSection(ConfigurationConstants.PackageSources).Returns(packageSourceSection); settings.GetSection(ConfigurationConstants.CredentialsSectionName).Returns(credentialSection); var configuration = new CakeConfiguration(new Dictionary <string, string>() { [Constants.NuGet.Source] = string.Empty, }); var provider = new NuGetSourceRepositoryProvider(settings, configuration, package); Assert.Single(provider.GetRepositories()); Assert.Contains(provider.GetRepositories(), p => p.PackageSource.Source == feed && p.PackageSource.Credentials.Username == "*****@*****.**" && p.PackageSource.Credentials.Password == "p455w0rdz"); }
#pragma warning restore 67 public void RaisePackageRestoreFailedEvent(Exception exception, string projectName) { var packageReference = new PackageReference( new PackageIdentity("Test", new NuGetVersion("1.2")), new NuGetFramework("any") ); var eventArgs = new PackageRestoreFailedEventArgs( packageReference, exception, new [] { projectName } ); PackageRestoreFailedEvent?.Invoke(this, eventArgs); }
private static string TryLocatePackage(DirectoryInfo packageRootDirectory, PackageReference packageReference) { var packageName = packageReference.Id + "." + packageReference.Version.ToString(); string nupkgPath = Path.Combine(packageRootDirectory.FullName, packageName, packageName + ".nupkg"); if (File.Exists(nupkgPath)) { return(nupkgPath); } else { return(null); } }
public void ProcessRecord_UpdatePackageInAllProjects_PackageVersionPassedToAction() { CreateCmdletWithActivePackageSourceAndProject(); SetIdParameter("MyPackage"); var expectedVersion = new SemanticVersion("1.0"); SetVersionParameter(expectedVersion); RunCmdlet(); PackageReference packageReference = fakeUpdateActionsFactory.PackageReferencePassedToCreateUpdatePackageInAllProjects; Assert.AreEqual(expectedVersion, packageReference.Version); }
/// <summary> /// This is the runner which dequeues package references from <paramref name="packageReferencesQueue" />, and /// performs copying of satellite files /// Note that this method should only Dequeue from the concurrent queue and not Enqueue /// </summary> private static async Task CopySatelliteFilesRunnerAsync(ConcurrentQueue <PackageReference> packageReferencesQueue, PackageRestoreContext packageRestoreContext, INuGetProjectContext nuGetProjectContext) { PackageReference currentPackageReference = null; while (packageReferencesQueue.TryDequeue(out currentPackageReference)) { var result = await packageRestoreContext.PackageManager.CopySatelliteFilesAsync( currentPackageReference.PackageIdentity, nuGetProjectContext, packageRestoreContext.Token); } }
private IProject GetProject(SolutionContext context, string name) { if (!_solution.ProjectCache.TryGetValue(name, out var project)) { var projectContext = context.GetProject(name); project = _projectFactoryFunc(projectContext.FileName); project.Name = projectContext.Name; project.Version = projectContext.Version; _solution.ProjectCache[projectContext.FileName] = project; foreach (var packageReferenceContext in projectContext.PackageReferences) { if (!_packageCache.PackagesDictionary.TryGetValue(packageReferenceContext.Name, out var package)) { package = _packageFactoryFunc(packageReferenceContext.Name); _packageCache.PackagesDictionary[packageReferenceContext.Name] = package; } var reference = new PackageReference { Package = package, Version = packageReferenceContext.Version, PreReleaseSuffix = packageReferenceContext.PreRelease }; if (project.PackageReferenceDictionary.TryGetValue(reference.Package.Name, out var existingReference)) { _logger.Error(project, $"There is already a reference to package {existingReference.Package.Name} at version {existingReference.Version}"); } project.PackageReferenceDictionary[reference.Package.Name] = reference; } foreach (var projectReferenceContext in projectContext.ProjectReferences) { if (!_solution.ProjectCache.TryGetValue(projectReferenceContext.FileName, out var subProject)) { subProject = GetProject(context, projectReferenceContext.FileName); } project.Projects.Add(subProject); subProject.Dependencies.Add(project); } } return(project); }
public override Task <bool> InstallPackageAsync(PackageIdentity packageIdentity, Stream packageStream, INuGetProjectContext nuGetProjectContext, CancellationToken token) { if (packageIdentity == null) { throw new ArgumentNullException("packageIdentity"); } if (nuGetProjectContext == null) { throw new ArgumentNullException("nuGetProjectContext"); } var newPackageReference = new PackageReference(packageIdentity, TargetFramework); List <PackageReference> installedPackagesList = GetInstalledPackagesList(); var packageReferenceWithSameId = installedPackagesList.Where(p => p.PackageIdentity.Id.Equals(packageIdentity.Id, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); if (packageReferenceWithSameId != null) { if (packageReferenceWithSameId.PackageIdentity.Equals(packageIdentity)) { nuGetProjectContext.Log(MessageLevel.Warning, Strings.PackageAlreadyExistsInPackagesConfig, packageIdentity, Path.GetFileName(FullPath)); return(Task.FromResult(false)); } else { // Higher version of an installed package is being installed. Remove old and add new installedPackagesList.Remove(packageReferenceWithSameId); installedPackagesList.Add(newPackageReference); } } else { installedPackagesList.Add(newPackageReference); } // Create new file or overwrite existing file using (var stream = FileSystemUtility.CreateFile(FullPath, nuGetProjectContext)) { var writer = new PackagesConfigWriter(stream); foreach (var pr in installedPackagesList) { writer.WritePackageEntry(pr); } writer.Close(); } nuGetProjectContext.Log(MessageLevel.Info, Strings.AddedPackageToPackagesConfig, packageIdentity, Path.GetFileName(FullPath)); return(Task.FromResult(true)); }
/// <summary> /// Attempts to return an already resolved Id/VersionConstraint pair from the cache. Attempts to prevent unecessary network calls. /// </summary> /// <param name="packageReference"></param> /// <param name="package"></param> /// <returns></returns> public bool TryCacheHitByVersionConstraint(PackageReference packageReference, out IPackage package) { if (_latestPackageConstraintCache.ContainsKey(packageReference.Id)) { if (_latestPackageConstraintCache[packageReference.Id].ContainsKey(packageReference.VersionConstraint)) { package = _latestPackageConstraintCache[packageReference.Id][packageReference.VersionConstraint]; _console.Log(MessageLevel.Info, "Using cached latest constrained version : {0} {1} using constraint {2}", package.Id, package.Version.ToString(), packageReference.VersionConstraint); return true; } } package = null; return false; }
public NuGetPackageInstallerFixture() { Environment = FakeEnvironment.CreateUnixEnvironment(); FileSystem = new FakeFileSystem(Environment); ProcessRunner = Substitute.For <IProcessRunner>(); ContentResolver = Substitute.For <INuGetPackageContentResolver>(); Log = Substitute.For <ICakeLog>(); ToolResolver = Substitute.For <INuGetToolResolver>(); ToolResolver.ResolvePath().Returns(new FilePath("/Working/tools/nuget.exe")); Package = new PackageReference("nuget:https://myget.org/temp/?package=Cake.Foo&prerelease&version=1.2.3"); PackageType = PackageType.Addin; InstallPath = new DirectoryPath("./nuget"); }
private static void AssertAreEqual(string expected, PackageReference resolvedVs) { if (expected == null) Assert.IsNull(resolvedVs); else { var expectedVs = VersionUtility.ParseVersionSpec(expected); var iSpec = resolvedVs.VersionConstraint as IVersionSpec; //TODO Equality comparer, anyone? This is pretty crappy.... Assert.AreEqual(expectedVs.IsMaxInclusive, iSpec.IsMaxInclusive); Assert.AreEqual(expectedVs.IsMinInclusive, iSpec.IsMinInclusive); Assert.AreEqual(expectedVs.MaxVersion, iSpec.MaxVersion); Assert.AreEqual(expectedVs.MinVersion, iSpec.MinVersion); } }
public PackageReferenceNode( ProjectPackagesFolderNode parentNode, PackageReference packageReference, bool installed, bool pending = false, PackageIdentity updatedPackage = null) { ParentNode = parentNode; PackageReference = packageReference; Installed = installed; IsInstallPending = pending; UpdatedVersion = GetUpdatedPackageVersion(updatedPackage); IsReinstallNeeded = packageReference.RequireReinstallation; }
private static string GetValue(this PackageReference package, string key, params char[] trimChars) { var hasValue = package.HasValue(key); if (!hasValue) { return(string.Empty); } var value = package.Parameters[key].FirstOrDefault(); return(value != null && trimChars.Any() ? value.Trim(trimChars) : value); }
public void Should_Ignore_Trailing_Separator_For_NuGet_Source_Argument() { var nugetV2Api = "https://packages.nuget.org/api/v2"; var package = new PackageReference("nuget:?package=First.Package"); var settings = Substitute.For <ISettings>(); var configuration = new CakeConfiguration(new Dictionary <string, string>() { [Constants.NuGet.Source] = nugetV2Api + ";", }); var provider = new NuGetSourceRepositoryProvider(settings, configuration, package); Assert.Single(provider.GetRepositories()); Assert.Contains(provider.GetRepositories(), p => p.PackageSource.Source == nugetV2Api); }
public object Execute(IScriptExecutor repl, object[] args) { Guard.AgainstNullArgument("repl", repl); if (args == null || args.Length == 0) { return null; } string version = null; var allowPre = false; if (args.Length >= 2) { version = args[1].ToString(); } allowPre = args.Length >= 3 && args[2].ToString().ToUpperInvariant() == "PRE"; _logger.InfoFormat("Installing {0}", args[0]); _installationProvider.Initialize(); var packageRef = new PackageReference( args[0].ToString(), new FrameworkName(".NETFramework,Version=v4.0"), version); _packageInstaller.InstallPackages(new[] { packageRef }, allowPre); _packageAssemblyResolver.SavePackages(); var dlls = _packageAssemblyResolver.GetAssemblyNames(repl.FileSystem.CurrentDirectory) .Except(repl.References.PathReferences).ToArray(); repl.AddReferences(dlls); foreach (var dll in dlls) { _logger.InfoFormat("Added reference to {0}", dll); } return null; }
public PackageReferenceMarker(TaskProvider taskProvider, PackageReference packageReference) { this._taskProvider = taskProvider; this.PackageReference = packageReference; }
/// <summary> /// If the package version is already installed then there is no need to install the /// NuGet package. /// </summary> bool ShouldRemoveExistingPackageReference (PackageReference packageReference, PackageIdentity packageIdentity) { var existingPackageReference = packageReference.ToNuGetPackageReference (); return !VersionComparer.Default.Equals (existingPackageReference.PackageIdentity.Version, packageIdentity.Version); }
public void CanResolveInstallablePackages() { var console = new Mock<ILogger>().Object; var resolver = new PackageResolutionManager(console, true, new MemoryBasedPackageCache(console)); var remoteRepository = Utilities.GetFactory().CreateRepository("SingleAggregate"); var packageReference = new PackageReference("Assembly.Common", SemanticVersion.Parse("1.0"), new VersionSpec()); var test = resolver.ResolveLatestInstallablePackage(remoteRepository, packageReference); Assert.AreEqual("Assembly.Common", test.Id); }
//TODO HACK HACK #WTF #EVIL Check the access to a private property. This requires a change to the PackageReferenceFile otherwise, which would take a long time..... /// <summary> /// Logs the satisfaction failure. /// </summary> /// <param name="p">The p.</param> /// <param name="prf">The PRF.</param> private void LogSatisfactionFailure(PackageReference p, PackageReferenceFile prf) { Console.WriteError("{0} {1}{2} in {3} could not be satisfied.", p.Id, p.Version, p.VersionConstraint != null ? " using constraint " + p.VersionConstraint : string.Empty, GetPackageConfigLocationUsingUltimateEvil(prf)); }
public override async Task<bool> InstallPackageAsync ( PackageIdentity packageIdentity, DownloadResourceResult downloadResourceResult, INuGetProjectContext nuGetProjectContext, CancellationToken token) { return await Runtime.RunInMainThread (async () => { // Check if this NuGet package is already installed and should be removed. PackageReference existingPackageReference = project.FindPackageReference (packageIdentity); if (existingPackageReference != null) { if (ShouldRemoveExistingPackageReference (existingPackageReference, packageIdentity)) { project.PackageReferences.Remove (existingPackageReference); } else { nuGetProjectContext.Log ( MessageLevel.Info, GettextCatalog.GetString ("Package '{0}' already installed.", packageIdentity)); return true; } } bool developmentDependency = false; if (IsNuGetBuildPackagingPackage (packageIdentity)) { await GlobalPackagesExtractor.Extract (project.ParentSolution, packageIdentity, downloadResourceResult, token); developmentDependency = true; GenerateNuGetBuildPackagingTargets (packageIdentity); } var packageReference = new PackageReference (packageIdentity); if (developmentDependency) packageReference.PrivateAssets = "All"; project.PackageReferences.Add (packageReference); await SaveProject (); return true; }); }
/// <summary> /// Resolves the installable version. /// </summary> /// <param name="remoteRepository"> </param> /// <param name="packageReference"> </param> /// <returns></returns> public IPackage ResolveLatestInstallablePackage(IPackageRepository remoteRepository, PackageReference packageReference) { IPackage package = null; if (Latest) { //We can only work on an AggregateRepository, just return null if we dont get one. var aggregateRepository = remoteRepository as AggregateRepository; if (aggregateRepository == null) return null; var versionSpecComparer = new VersionSpecEqualityComparer(packageReference.VersionConstraint); var defaultVersionSpec = new VersionSpec(); if (versionSpecComparer.Equals(defaultVersionSpec)) { //First, check to see if we have already checked for this ID, and if so, return the right version if (_cache.TryCacheHitByIsLatest(packageReference.Id, out package)) return package; //TODO need to check where we need to get the bools for this call....assuming a bit much here. Console.Log(MessageLevel.Info, "Checking for latest package: {0}", packageReference.Id); try { IPackage p = aggregateRepository.FindLatestPackage(packageReference.Id); if (p != null) { Console.Log(MessageLevel.Info, "Using latest version : {0} {1}", p.Id, p.ToString()); //Only add if there is no constraint.... _cache.AddCacheEntryByIsLatest(p); package = p; } else { Console.Log(MessageLevel.Info, "Latest version requested, however {0} cannot be found on feed.", packageReference.Id); return null; } } catch (NullReferenceException) { Console.Log(MessageLevel.Error, "One of the feeds threw an error, a package called {0} could not be found.", packageReference.Id); return null; } } else { Console.Log(MessageLevel.Info, "Checking for latest package: {0} using constraint {1}", packageReference.Id, packageReference.VersionConstraint); if (_cache.TryCacheHitByVersionConstraint(packageReference, out package)) return package; try { IPackage p = aggregateRepository.FindLatestPackage(packageReference.Id, packageReference.VersionConstraint); if (p != null) { package = p; _cache.AddCacheEntryByConstraint(package, packageReference.VersionConstraint); Console.Log(MessageLevel.Info, "Using constrained version : {0} {1}, constrained by {2}", packageReference.Id, p.Version.ToString(), packageReference.VersionConstraint); } else { Console.Log(MessageLevel.Error, "Latest version requested, however {0} cannot be satisfied on feed using constraint {1}.", packageReference.Id, packageReference.VersionConstraint); return null; } } catch (NullReferenceException) { Console.Log(MessageLevel.Error, "One of the feeds threw an error, a package called {0} could not be found.", packageReference.Id); return null; } } } return package; }
/// <summary> /// Restores the given package into the packages folder represented by 'fileSystem'. /// </summary> /// <param name="package">The package to be restored.</param> private void RestorePackage(PackageReference package) { WriteLine(VerbosityLevel.Normal, Resources.RestoringPackage, package); // during package restore, use local cache as the primary source, other sources // as secondary source. IVsPackageManagerFactory packageManagerFactory = ServiceLocator.GetInstance<IVsPackageManagerFactory>(); var allSources = packageManagerFactory.CreatePackageManagerWithAllPackageSources().SourceRepository; var repository = new PriorityPackageRepository(NuGet.MachineCache.Default, allSources); var packageManager = packageManagerFactory.CreatePackageManager(repository, useFallbackForDependencies: false); using (packageManager.SourceRepository.StartOperation(RepositoryOperationNames.Restore, package.Id, package.Version.ToString())) { var resolvedPackage = PackageHelper.ResolvePackage( packageManager.SourceRepository, package.Id, package.Version); NuGet.Common.PackageExtractor.InstallPackage(packageManager, resolvedPackage); WriteLine(VerbosityLevel.Normal, Resources.PackageRestored, resolvedPackage); } }
/// <summary> /// Attempts to resolve a package reference based on a reference name. /// </summary> /// <param name="referenceName">The reference name</param> /// <param name="package">The package reference, if the <paramref name="referenceName"/> /// matches a NuGet package reference name or one of the assemblies referenced by the package; otherwise, null.</param> /// <returns>True if a match is found; otherwise, null.</returns> public bool TryGetPackageReference(string referenceName, out PackageReference package) { if (_assemblyExtensions.Contains(Path.GetExtension(referenceName))) { referenceName = Path.GetFileNameWithoutExtension(referenceName); } package = _packageAssemblyResolver.Packages.FirstOrDefault(p => string.Compare(referenceName, p.Name, StringComparison.OrdinalIgnoreCase) == 0 || p.Assemblies.Keys.Any(a => string.Compare(a.Name, referenceName) == 0)); return package != null; }
/// <summary> /// Installs the packages from config file. /// </summary> /// <param name="fileSystem">The file system.</param> /// <param name="file">The file.</param> /// <param name="target"> </param> private IEnumerable<PackageReference> InstallPackagesFromConfigFile(string packagesDirectory, PackageReferenceFile file, string target) { var packageReferences = file.GetPackageReferences().ToList(); var installedPackages = new List<PackageReference>(); var allInstalled = new List<PackageReference>(); //We need to create a damn filesystem at the packages directory, so that the ROOT is correct. Ahuh... var fileSystem = CreateFileSystem(packagesDirectory); if (!NoCache) Console.WriteLine("Using cache...."); PackageManager packageManager = CreatePackageManager(fileSystem, useMachineCache: !NoCache); if (Clean) packageManager.CleanPackageFolders(); bool installedAny = false; foreach (var packageReference in packageReferences) { if (String.IsNullOrEmpty(packageReference.Id)) { // GetPackageReferences returns all records without validating values. We'll throw if we encounter packages // with malformed ids / Versions. throw new InvalidDataException(String.Format(CultureInfo.CurrentCulture, GetResources.GetCommandInvalidPackageReference, target)); } else if (packageReference.Version == null) { throw new InvalidDataException(String.Format(CultureInfo.CurrentCulture, GetResources.GetCommandPackageReferenceInvalidVersion, packageReference.Id)); } packageManager.PackageInstalled += (sender, e) => { var installedPackage = new PackageReference(e.Package.Id, e.Package.Version, null, _frameworkName, false); if (!allInstalled.Contains(installedPackage)) allInstalled.Add(installedPackage); }; IPackage package = _packageResolutionManager.ResolveLatestInstallablePackage(_repository, packageReference); if (package == null) { SemanticVersion version = _packageResolutionManager.ResolveInstallableVersion(_repository, packageReference); installedAny |= InstallPackage(packageManager, fileSystem, packageReference.Id, version ?? packageReference.Version); installedPackages.Add(new PackageReference(packageReference.Id, version ?? packageReference.Version, null, _frameworkName, false)); } else { //We got it straight from the server, check whether we get a cache hit, else just install var resolvedPackage = _packageResolutionManager.FindPackageInAllLocalSources(packageManager.LocalRepository, packageManager.SourceRepository, package); packageManager.InstallPackage(resolvedPackage ?? package, !IncludeDependencies, false); installedPackages.Add(new PackageReference(package.Id, resolvedPackage != null ? resolvedPackage.Version : package.Version, null, _frameworkName, false)); } // Note that we ignore dependencies here because packages.config already contains the full closure } if (!installedAny && packageReferences.Any()) { Console.WriteLine(GetResources.GetCommandNothingToInstall, Constants.PackageReferenceFile); } if (packageReferences != installedPackages) { foreach (var reference in file.GetPackageReferences()) file.DeleteEntry(reference.Id, reference.Version); foreach (var installedPackage in installedPackages) { file.AddEntry(installedPackage.Id,installedPackage.Version); } } return allInstalled; }
public void WhenStringVersionHasNormalValueVersionShouldBeEqualToThat() { var p = new PackageReference("packageId", new FrameworkName(".NETFramework,Version=v4.0"), "1.0.1"); p.Version.ShouldEqual(new Version("1.0.1")); }
public void WhenStringVersionHasSpecialValueVersionShouldBeEqualToNormalAndSpecialVersionShouldBeSet() { var p = new PackageReference("packageId", new FrameworkName(".NETFramework,Version=v4.0"), "1.0.1-alpha"); p.Version.ShouldEqual(new Version("1.0.1")); p.SpecialVersion.ShouldEqual("alpha"); }
public void InstallsPackageUsingArg1AsVersion() { // arrange var cmd = GetCommand(); // act cmd.Execute(_repl.Object, new[] { "scriptcs", "0.9" }); // assert var packageRef = new PackageReference("scriptcs", new FrameworkName(".NETFramework,Version=v4.0"), "0.9"); _packageInstaller.Verify( x => x.InstallPackages( It.Is<IEnumerable<IPackageReference>>(i => i.ElementAt(0).Version == packageRef.Version), false), Times.Once); }
private void ExecuteOk(object sender, EventArgs e) { foreach (var packageNsolution in _solutions) { var package = packageNsolution.Key; var solution = packageNsolution.Value; var packageReference = new PackageReference(package, solution.LibraryReferences); Module.RemoveExistingSimilarPackages(packageReference, solution.CheckedProjects); Module.ManagePackage(packageReference, solution.CheckedProjects, solution.LibraryReferences); } Module.HideVisualStudioControl(); Module.ReloadMainControl(); if (Module.PackageManager.UpdatePlan.Any() || Module.PackageManager.InstallPlan.Any() || Module.PackageManager.RemovePlan.Any()) Module.ShowSummaryControl(); else Module.ShowMainControl(); }
/// <summary> /// Resolves the installable version. /// </summary> /// <param name="remoteRepository"> </param> /// <param name="packageReference">The package.</param> /// <returns></returns> public SemanticVersion ResolveInstallableVersion(IPackageRepository remoteRepository, PackageReference packageReference) { IPackage package; if (Latest) { package = ResolveLatestInstallablePackage(remoteRepository, packageReference); return package != null ? package.Version : null; } Console.Log(MessageLevel.Info, "Using specific version : {0} {1}", packageReference.Id, packageReference.Version.ToString()); return packageReference.Version; }
/// <summary> /// Restores the given package into the packages folder represented by 'fileSystem'. /// </summary> /// <param name="package">The package to be restored.</param> /// <param name="fileSystem">The file system representing the packages folder.</param> private void RestorePackage(PackageReference package, IFileSystem fileSystem) { WriteLine(VerbosityLevel.Normal, Resources.RestoringPackage, package); IVsPackageManagerFactory packageManagerFactory = ServiceLocator.GetInstance<IVsPackageManagerFactory>(); var packageManager = packageManagerFactory.CreatePackageManager(); if (IsPackageInstalled(packageManager.LocalRepository, fileSystem, package.Id, package.Version)) { WriteLine(VerbosityLevel.Normal, Resources.SkipInstalledPackage, package); return; } if (_isConsentGranted) { using (packageManager.SourceRepository.StartOperation(RepositoryOperationNames.Restore)) { var resolvedPackage = PackageHelper.ResolvePackage( packageManager.SourceRepository, package.Id, package.Version); NuGet.Common.PackageExtractor.InstallPackage(packageManager, resolvedPackage); WriteLine(VerbosityLevel.Normal, Resources.PackageRestored, resolvedPackage); } } else { WriteLine(VerbosityLevel.Quiet, Resources.PackageNotRestoredBecauseOfNoConsent, package); } }
public static void ManagePackage(PackageReference packageReference, IEnumerable<Project> checkedProjects, IEnumerable<LibraryReference> libraries) { if (!IsSolutionOpen) return; foreach (var project in DTE.Solution.Projects.OfType<Project>().Where(n => n.IsSupported())) { var resultLibraries = Enumerable.Empty<LibraryReference>(); var projectLibraries = libraries.Where(n => n.ProjectName == project.GetName()); switch (packageReference.Type) { case DeveloperLibraryType.VcInclude: project.ManageIncludeDirectories(packageReference, checkedProjects); break; case DeveloperLibraryType.VcLibrary: project.ManageLinkerDefinitions(packageReference, checkedProjects, projectLibraries); resultLibraries = projectLibraries.Where(n => n.IsChecked); break; case DeveloperLibraryType.Net: project.ManageReferences(packageReference, projectLibraries); resultLibraries = projectLibraries.Where(n => n.IsChecked); break; } var packageReferenceFile = new PackageReferenceFile(project.GetDirectory() + "/coapp.packages.config"); if (checkedProjects.Any(n => n.FullName == project.FullName)) { packageReferenceFile.AddEntry(packageReference.CanonicalName, resultLibraries, packageReference.Type); } else { packageReferenceFile.DeleteEntry(packageReference.CanonicalName); } project.Save(project.FullName); } }
/// <summary> /// Resolves the largest valid VersionSpec across a set of PackageReference objects. /// </summary> /// <param name="packageReferences">The package references.</param> /// <returns></returns> internal PackageReference ResolveValidVersionSpec(IEnumerable<PackageReference> packageReferences) { if (packageReferences.Count() != 0) { var failures = new List<PackageReference>(); SemanticVersion winner = null; VersionSpec smallest = ReturnLargestVersionSpec(); string id = packageReferences.First().Id; foreach (var pr in packageReferences) { //First, does this VersionSpec sit completely outside the range of the existing smallest set? bool minGreaterThanCurrentMax = smallest.IsMaxInclusive && pr.VersionConstraint.IsMinInclusive ? pr.VersionConstraint.MinVersion > smallest.MaxVersion : pr.VersionConstraint.MinVersion >= smallest.MaxVersion; bool maxLessThanCurrentMin = smallest.IsMinInclusive && pr.VersionConstraint.IsMaxInclusive ? pr.VersionConstraint.MaxVersion < smallest.MinVersion : pr.VersionConstraint.MaxVersion <= smallest.MinVersion; if (minGreaterThanCurrentMax || maxLessThanCurrentMin) { failures.Add(pr); } else { //Now, is it more restrictive than the smallest? bool minMoreConstrictive = (!pr.VersionConstraint.IsMinInclusive && smallest.IsMinInclusive && (pr.VersionConstraint.MinVersion == smallest.MinVersion)) || pr.VersionConstraint.MinVersion > smallest.MinVersion; bool maxMoreConstrictive = (!pr.VersionConstraint.IsMaxInclusive && smallest.IsMaxInclusive && (pr.VersionConstraint.MaxVersion == smallest.MaxVersion)) || pr.VersionConstraint.MaxVersion < smallest.MaxVersion; if (minMoreConstrictive) { smallest.MinVersion = pr.VersionConstraint.MinVersion; smallest.IsMinInclusive = pr.VersionConstraint.IsMinInclusive; winner = pr.Version; } if (maxMoreConstrictive) { smallest.MaxVersion = pr.VersionConstraint.MaxVersion; smallest.IsMaxInclusive = pr.VersionConstraint.IsMaxInclusive; winner = pr.Version; } } } //If we get no failures, set the ResolvedVersionSpec, otherwise it stays at null if (failures.Count == 0) { var pr = new PackageReference(id, winner, smallest); return pr; } } return null; }
public static void RemoveExistingSimilarPackages(PackageReference packageReference, IEnumerable<Project> checkedProjects) { foreach (var project in DTE.Solution.Projects.OfType<Project>().Where(n => n.IsSupported())) { if (!checkedProjects.Any(n => n.Name == project.Name)) continue; var packageReferenceFile = new PackageReferenceFile(project.GetDirectory() + "/coapp.packages.config"); var packageReferences = packageReferenceFile.GetPackageReferences(); foreach (var packageRef in packageReferences) { if (packageRef.CanonicalName.Name != packageReference.CanonicalName.Name || packageRef.CanonicalName.Architecture != packageReference.CanonicalName.Architecture) continue; var removedLibraries = new List<LibraryReference>(); foreach (var lib in packageRef.Libraries) { removedLibraries.Add(new LibraryReference(lib.Name, project.GetName(), lib.ConfigurationName, false)); } ManagePackage(packageRef, new Project[0], removedLibraries); } } }
public PackageReference GetPackageReference(string packageId) { var package = GetPackages().Where(p => string.Equals(p.Id, packageId, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); if (package == null) { return null; } var packageReference = new PackageReference( package.Id, package.Version, versionConstraint: null, targetFramework: null, isDevelopmentDependency: false); return packageReference; }
public void WhenStringVersionIsEmptyVersionShouldBeEmpty() { var p = new PackageReference("packageId", new FrameworkName(".NETFramework,Version=v4.0"), ""); p.Version.ShouldEqual(new Version()); }