public static void InstallPackage(string subFolder, PackageReference package  )
        {
            var logger = LogManager.GetCurrentClassLogger();

              string packagePath = Path.GetFullPath( Path.Combine( subFolder, FindRelativePathOfPackagesFolder( subFolder ) ) );

              // TODO: Use NuGet API for this!
              logger.Info( "Installing nuget package " + package.PackageIdentity + " to " + Path.GetFullPath( packagePath ) );
              var nugetExe = GetNugetExePath();

              var processStartInfo = new ProcessStartInfo( nugetExe, "install " + package.PackageIdentity.Id + " -Version " + package.PackageIdentity.Version + " -Pre" );
              processStartInfo.RedirectStandardOutput = true;
              processStartInfo.RedirectStandardError = true;

              Directory.CreateDirectory( packagePath );

              processStartInfo.WorkingDirectory = packagePath;
              processStartInfo.UseShellExecute = false;
              processStartInfo.CreateNoWindow = true;

              var process = Process.Start( processStartInfo );
              logger.Info( process.StandardOutput.ReadToEnd() );
              logger.Info( process.StandardError.ReadToEnd() );

              if ( process.ExitCode != 0 ) {
            var exception = new Exception( "Failed to execute " + processStartInfo.FileName + " " + processStartInfo.Arguments );
            logger.Error( exception );
            throw exception;
              }
        }
 public ConfigitPackageReference( string id, string version, string targetFramework = null, string allowedVersion = null, bool userInstalled = false )
 {
     _reference = new PackageReference(
     new PackageIdentity( id, new NuGetVersion( version ) ),
     targetFramework == null ? null : new NuGetFramework( targetFramework ),
     userInstalled, false, false, allowedVersion != null ? VersionRange.Parse( allowedVersion ) : null );
 }
		void CreatePackageReference (
			string packageId = "Id",
			string packageVersion = "1.2.3",
			bool requireReinstallation = false)
		{
			var version = new NuGetVersion (packageVersion);
			var identity = new PackageIdentity (packageId, version);
			packageReference = new PackageReference (identity, null, true, false, requireReinstallation);
		}
 // TODO: Consider removing elements from the collection and check if that is better in performance
 public static IEnumerable<SourceDependencyInfo> RemoveDisallowedVersions(IEnumerable<SourceDependencyInfo> packages, PackageReference packageReference)
 {
     if (packageReference.AllowedVersions != null)
     {
         return packages.Where(p => !StringComparer.OrdinalIgnoreCase.Equals(p.Id, packageReference.PackageIdentity.Id)
         || packageReference.AllowedVersions.Satisfies(p.Version));
     }
     return packages;
 }
Ejemplo n.º 5
0
        public PackageReference ReTarget( PackageReference reference )
        {
            if ( !IsTargeted( reference.PackageIdentity.Id ) ) {
            return reference;
              }

              return new PackageReference(
            new PackageIdentity( reference.PackageIdentity.Id, TargetVersion ?? reference.PackageIdentity.Version ),
            TargetFramework ??
            reference.TargetFramework, reference.IsUserInstalled, reference.IsDevelopmentDependency, reference.RequireReinstallation );
        }
Ejemplo n.º 6
0
		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);
		}
		#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);
		}
Ejemplo n.º 8
0
        public async Task GetInstalledPackagesAsync_WhenProjectReturnsNullPackageReference_NullIsRemoved()
        {
            const string projectName = "a";
            string       projectId   = Guid.NewGuid().ToString();

            using (TestDirectory testDirectory = TestDirectory.Create())
            {
                Initialize();

                string         projectFullPath           = Path.Combine(testDirectory.Path, $"{projectName}.csproj");
                NuGetFramework targetFramework           = NuGetFramework.Parse("net46");
                var            msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(targetFramework, new TestNuGetProjectContext());
                var            project          = new TestMSBuildNuGetProject(msBuildNuGetProjectSystem, testDirectory.Path, projectFullPath, projectId);
                var            packageReference = new PackageReference(
                    new PackageIdentity(id: "b", NuGetVersion.Parse("1.0.0")),
                    targetFramework);
                project.InstalledPackageReferences = Task.FromResult <IEnumerable <PackageReference> >(new[]
                {
                    null,
                    packageReference
                });

                _solutionManager.NuGetProjects.Add(project);

                var telemetrySession = new Mock <ITelemetrySession>();
                var telemetryEvents  = new ConcurrentQueue <TelemetryEvent>();

                telemetrySession
                .Setup(x => x.PostEvent(It.IsAny <TelemetryEvent>()))
                .Callback <TelemetryEvent>(x => telemetryEvents.Enqueue(x));

                TelemetryActivity.NuGetTelemetryService = new NuGetVSTelemetryService(telemetrySession.Object);

                IReadOnlyCollection <IPackageReferenceContextInfo> packages = await _projectManager.GetInstalledPackagesAsync(
                    new[] { projectId },
                    CancellationToken.None);

                Assert.Equal(1, packages.Count);
                IPackageReferenceContextInfo expected = PackageReferenceContextInfo.Create(packageReference);
                IPackageReferenceContextInfo actual   = packages.Single();

                Assert.Equal(expected.AllowedVersions, actual.AllowedVersions);
                Assert.Equal(expected.Framework, actual.Framework);
                Assert.Equal(expected.Identity, actual.Identity);
                Assert.Equal(expected.IsAutoReferenced, actual.IsAutoReferenced);
                Assert.Equal(expected.IsDevelopmentDependency, actual.IsDevelopmentDependency);
                Assert.Equal(expected.IsUserInstalled, actual.IsUserInstalled);

                Assert.Equal(1, telemetryEvents.Count);
            }
        }
		public void AddUnrestoredPackageForProject (string projectName, string solutionDirectory)
		{
			var packageReference = new PackageReference (
				new PackageIdentity ("Test", new NuGetVersion ("1.0")),
				new NuGetFramework ("any"));

			var restoreData = new PackageRestoreData (
				packageReference,
				new [] { projectName },
				isMissing: true);

			var restoreDataList = new List<PackageRestoreData> ();
			restoreDataList.Add (restoreData);
			PackagesInSolution[solutionDirectory] = restoreDataList;
		}
Ejemplo n.º 10
0
        private XElement ReplacePackageAttributes(XElement existingNode, PackageReference newEntry)
        {
            var newEntryNode = CreateXElementForPackageEntry(newEntry);

            var newAttributeNames      = newEntryNode.Attributes().Select(a => a.Name);
            var existingAttributeNames = existingNode.Attributes().Select(a => a.Name);
            var addableAttributeNames  = newAttributeNames.Except(existingAttributeNames);

            foreach (XName name in existingAttributeNames)
            {
                // Clear newValue
                string newValue = null;

                // Try to get newValue correlated to the attribute on the existing node.
                PackagesConfig.TryGetAttribute(newEntryNode, name.LocalName, out newValue);

                // When the attribute is not specified a value in the new node
                if (string.IsNullOrEmpty(newValue))
                {
                    if (name.Equals(XName.Get(PackagesConfig.RequireInstallAttributeName)))
                    {
                        // Remove the requirementReinstallation attribute.
                        existingNode.SetAttributeValue(name, value: null);
                    }
                    else
                    {
                        // no-op. Keep the allowedVersion attribute and all other attributes as-is.
                    }
                }
                else
                {
                    // Replace existing attributes with new values
                    existingNode.SetAttributeValue(name, newValue);
                }
            }

            // Add new attributes that was not in the old package reference entry, if any
            foreach (XName name in addableAttributeNames)
            {
                var attribute = new XAttribute(name, newEntryNode.Attribute(name).Value);
                existingNode.Add(attribute);
            }

            return(existingNode);
        }
Ejemplo n.º 11
0
        public PackageObject(NuGet.Packaging.PackageReference packageReference, FrameworkName frameworkName)
        {
            _packageReference = packageReference;
            FrameworkName     = frameworkName;
            Id          = _packageReference.PackageIdentity.Id;
            Version     = _packageReference.PackageIdentity.Version.Version;
            TextVersion = _packageReference.PackageIdentity.Version.ToString();
            //todo
            //FrameworkAssemblies = package.FrameworkAssemblies
            //    .Where(x => x.SupportedFrameworks.Any(y => y == frameworkName))
            //    .Select(x => x.AssemblyName);

            //todo
            //var dependencies = _packageReference..GetCompatiblePackageDependencies(frameworkName);
            //if (dependencies != null)
            //{
            //    Dependencies = dependencies.Select(i => new PackageObject(i.Id) { FrameworkName = frameworkName });
            //}
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Adds a package entry to the file
        /// </summary>
        /// <param name="entry">Package reference entry</param>
        public void WritePackageEntry(PackageReference entry)
        {
            if (entry == null)
            {
                throw new ArgumentNullException("entry");
            }

            if (_disposed || _closed)
            {
                throw new PackagingException("Writer closed. Unable to add entry.");
            }

            if (_entries.Where(e => StringComparer.OrdinalIgnoreCase.Equals(e.PackageIdentity.Id, entry.PackageIdentity.Id)).Any())
            {
                throw new PackagingException(String.Format(CultureInfo.InvariantCulture, "Package entry already exists. Id: {0}", entry.PackageIdentity.Id));
            }

            _entries.Add(entry);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Update a package entry using the original entry as a base if it exists.
        /// </summary>
        public void UpdateOrAddPackageEntry(XDocument originalConfig, PackageReference newEntry)
        {
            if (originalConfig == null)
            {
                throw new ArgumentNullException(nameof(originalConfig));
            }

            if (newEntry == null)
            {
                throw new ArgumentNullException(nameof(newEntry));
            }

            if (_disposed)
            {
                throw new PackagesConfigWriterException(string.Format(CultureInfo.CurrentCulture,
                                                                      Strings.UnableToAddEntry));
            }

            var originalPackagesNode = originalConfig.Element(XName.Get(PackagesConfig.PackagesNodeName));

            XElement matchingIdNode;

            if (PackagesConfig.HasAttributeValue(
                    originalPackagesNode,
                    PackagesConfig.IdAttributeName,
                    newEntry.PackageIdentity.Id,
                    out matchingIdNode))
            {
                // Find the old entry and update it based on the new entry
                var packagesNode   = _xDocument.Element(XName.Get(PackagesConfig.PackagesNodeName));
                var newPackageNode = ReplacePackageAttributes(matchingIdNode, newEntry);
                packagesNode.Add(newPackageNode);
                SortPackageNodes(packagesNode);
            }
            else
            {
                // There was no existing entry, add a new one
                AddPackageEntry(newEntry);
            }
        }
        public static FrameworkedHintPath ReconstructHintPath(
      string assemblyFilePath,
      PackageIdentity oldPackageIdentity,
      PackageReference newestPackage,
      Reference reference )
        {
            var parts = assemblyFilePath.Split( Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar ).ToList();

              var newFramework = parts.Select( NuGetFramework.Parse ).FirstOrDefault( f => !f.IsUnsupported );

              var hintParts = reference.HintPath.Split( Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar ).ToList();

              var oldFramework = hintParts.Select( NuGetFramework.Parse ).FirstOrDefault( f => !f.IsUnsupported );

              List<string> resultPath = new List<string>();

              for ( int i = hintParts.Count - 1; i >= 0; i-- ) {
            if ( hintParts[i].StartsWith( "$" ) ) {
              resultPath.Add( hintParts[i] );
            }
            else if ( hintParts[i].Equals( oldPackageIdentity.ToFolderName() ) ) {
              resultPath.Add( newestPackage.ToFolderName() );
            }
            else if ( oldFramework != null && newFramework != null && hintParts[i].Equals( oldFramework.GetShortFolderName(), StringComparison.OrdinalIgnoreCase ) ) {
              resultPath.Add( newFramework.GetShortFolderName() );
            }
            else {
              resultPath.Add( hintParts[i] );
            }
              }

              resultPath.Reverse();

              return new FrameworkedHintPath {
            Framework = newFramework,
            HintPath = Path.Combine( resultPath.ToArray() )
              };
        }
Ejemplo n.º 15
0
        private XElement CreateXElementForPackageEntry(PackageReference entry)
        {
            var node = new XElement(XName.Get(PackagesConfig.PackageNodeName));

            node.Add(new XAttribute(XName.Get(PackagesConfig.IdAttributeName), entry.PackageIdentity.Id));
            node.Add(new XAttribute(XName.Get(PackagesConfig.VersionAttributeName), entry.PackageIdentity.Version));

            // map the framework to the short name
            // special frameworks such as any and unsupported will be ignored here
            if (entry.TargetFramework.IsSpecificFramework)
            {
                var frameworkShortName = entry.TargetFramework.GetShortFolderName(_frameworkMappings);

                if (!String.IsNullOrEmpty(frameworkShortName))
                {
                    node.Add(new XAttribute(XName.Get(PackagesConfig.TargetFrameworkAttributeName), frameworkShortName));
                }
            }

            if (entry.HasAllowedVersions)
            {
                node.Add(new XAttribute(XName.Get(PackagesConfig.allowedVersionsAttributeName), entry.AllowedVersions.ToString()));
            }

            if (entry.IsDevelopmentDependency)
            {
                node.Add(new XAttribute(XName.Get(PackagesConfig.developmentDependencyAttributeName), "true"));
            }

            if (entry.RequireReinstallation)
            {
                node.Add(new XAttribute(XName.Get(PackagesConfig.RequireInstallAttributeName), "true"));
            }

            return(node);
        }
		void CreatePackageReferenceWithProjectJsonWildcardVersion (string packageId, string version)
		{
			packageReference = TestPackageReferenceFactory.CreatePackageReferenceWithProjectJsonWildcardVersion (
				packageId,
				version);
		}
Ejemplo n.º 17
0
        /// <summary>
        /// Reads all package node entries in the config
        /// </summary>
        /// <returns></returns>
        public IEnumerable <PackageReference> GetPackages()
        {
            var packages = new List <PackageReference>();

            foreach (var package in _doc.Root.Elements(XName.Get("package")))
            {
                string id = null;
                if (!TryGetAttribute(package, "id", out id) ||
                    String.IsNullOrEmpty(id))
                {
                    throw new PackagesConfigReaderException(string.Format(
                                                                CultureInfo.CurrentCulture,
                                                                Strings.ErrorNullOrEmptyPackageId));
                }

                string version = null;
                if (!TryGetAttribute(package, "version", out version) ||
                    String.IsNullOrEmpty(version))
                {
                    throw new PackagesConfigReaderException(string.Format(
                                                                CultureInfo.CurrentCulture,
                                                                Strings.ErrorInvalidPackageVersion,
                                                                id,
                                                                version));
                }

                NuGetVersion semver = null;
                if (!NuGetVersion.TryParse(version, out semver))
                {
                    throw new PackagesConfigReaderException(string.Format(
                                                                CultureInfo.CurrentCulture,
                                                                Strings.ErrorInvalidPackageVersion,
                                                                id,
                                                                version));
                }

                string       attributeValue  = null;
                VersionRange allowedVersions = null;
                if (TryGetAttribute(package, "allowedVersions", out attributeValue))
                {
                    if (!VersionRange.TryParse(attributeValue, out allowedVersions))
                    {
                        throw new PackagesConfigReaderException(string.Format(
                                                                    CultureInfo.CurrentCulture,
                                                                    Strings.ErrorInvalidAllowedVersions,
                                                                    id,
                                                                    attributeValue));
                    }
                }

                var targetFramework = NuGetFramework.UnsupportedFramework;
                if (TryGetAttribute(package, "targetFramework", out attributeValue))
                {
                    targetFramework = NuGetFramework.Parse(attributeValue, _frameworkMappings);
                }

                var developmentDependency = BoolAttribute(package, "developmentDependency");
                var requireReinstallation = BoolAttribute(package, "requireReinstallation");
                var userInstalled         = BoolAttribute(package, "userInstalled", true);

                var entry = new PackageReference(new PackageIdentity(id, semver), targetFramework, userInstalled, developmentDependency, requireReinstallation, allowedVersions);

                packages.Add(entry);
            }

            // check if there are duplicate entries
            var packageIds = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
            var duplicates = new List <string>();

            foreach (var package in packages)
            {
                if (packageIds.Contains(package.PackageIdentity.Id))
                {
                    duplicates.Add(package.PackageIdentity.Id);
                }
                else
                {
                    packageIds.Add(package.PackageIdentity.Id);
                }
            }

            if (duplicates.Count > 0)
            {
                throw new PackagesConfigReaderException(string.Format(
                                                            CultureInfo.CurrentCulture,
                                                            Strings.ErrorDuplicatePackages,
                                                            string.Join(", ", duplicates)));
            }

            return(packages);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Adds a package entry to the file
        /// </summary>
        /// <param name="entry">Package reference entry</param>
        public void WritePackageEntry(PackageReference entry)
        {
            if (entry == null)
            {
                throw new ArgumentNullException("entry");
            }

            if (_disposed || _closed)
            {
                throw new PackagingException("Writer closed. Unable to add entry.");
            }

            if (_entries.Where(e => StringComparer.OrdinalIgnoreCase.Equals(e.PackageIdentity.Id, entry.PackageIdentity.Id)).Any())
            {
                throw new PackagingException(String.Format(CultureInfo.InvariantCulture, "Package entry already exists. Id: {0}", entry.PackageIdentity.Id));
            }

            _entries.Add(entry);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Adds a basic package entry to the file
        /// </summary>
        public void WritePackageEntry(PackageIdentity identity, NuGetFramework targetFramework)
        {
            var entry = new PackageReference(identity, targetFramework);

            WritePackageEntry(entry);
        }
        public static Tuple<NuGetFramework, Reference> TryUpdateReference(
      string newFile,
      PackageIdentity oldPackageIdentity,
      PackageReference newestPackage,
      Reference reference, Func<string, AssemblyName> assemblyNameResolve = null )
        {
            assemblyNameResolve = assemblyNameResolve ?? AssemblyName.GetAssemblyName;

              var newHintPath = ReconstructHintPath( newFile, oldPackageIdentity, newestPackage, reference );

              if ( newHintPath == null ) {
            return null;
              }

              AssemblyName updatedName = assemblyNameResolve( newFile );

              string updatedInclude = IncludeFromAssemblyName( updatedName );

              return new Tuple<NuGetFramework, Reference>(
            newHintPath.Framework,
            new Reference( updatedInclude, reference.SpecificVersion, reference.Private, newHintPath.HintPath ) );
        }
		async Task<PackageIdentity> GetUpdates (SourceRepository sourceRepository, PackageReference packageReference)
		{
			var metadataResource = await sourceRepository.GetResourceAsync<PackageMetadataResource> (cancellationToken);

			if (metadataResource == null)
				return null;

			var packages = await metadataResource.GetMetadataAsync (
				packageReference.PackageIdentity.Id,
				includePrerelease: packageReference.PackageIdentity.Version.IsPrerelease,
				includeUnlisted: false,
				log: NullLogger.Instance,
				token: cancellationToken);

			var package = packages
				.Where (p => IsPackageVersionAllowed (p, packageReference))
				.OrderByDescending (p => p.Identity.Version).FirstOrDefault ();
			if (package == null)
				return null;

			if (package.Identity.Version > packageReference.PackageIdentity.Version)
				return package.Identity;

			return null;
		}
 /// <summary>
 /// Get update package identity when -Version is specified.
 /// </summary>
 /// <param name="project"></param>
 /// <param name="installedPackage"></param>
 /// <returns></returns>
 private PackageIdentity GetUpdatePackageIdentityWhenVersionSpecified(NuGetProject project, PackageReference installedPackage)
 {
     PackageIdentity update = null;
     // If Highest/HighestMinor/HighestPatch/Lowest is given after -version switch
     if (IsVersionEnum)
     {
         update = GetPackageUpdate(installedPackage, project, _allowPrerelease, false, null, true, _updateVersionEnum);
     }
     // If a NuGetVersion format is given after -version switch
     else
     {
         update = GetPackageUpdate(installedPackage, project, _allowPrerelease, false, Version);
     }
     return update;
 }
Ejemplo n.º 23
0
        /// <summary>
        /// Reads all package node entries in the config
        /// </summary>
        /// <returns></returns>
        public IEnumerable<PackageReference> GetPackages()
        {
            var packages = new List<PackageReference>();

            foreach (var package in _doc.Root.Elements(XName.Get("package")))
            {
                string id = null;
                if (!TryGetAttribute(package, "id", out id)
                    || String.IsNullOrEmpty(id))
                {
                    throw new PackagesConfigReaderException(string.Format(
                        CultureInfo.CurrentCulture,
                        Strings.ErrorNullOrEmptyPackageId));
                }

                string version = null;
                if (!TryGetAttribute(package, "version", out version)
                    || String.IsNullOrEmpty(version))
                {
                    throw new PackagesConfigReaderException(string.Format(
                       CultureInfo.CurrentCulture,
                       Strings.ErrorInvalidPackageVersion,
                       id,
                       version));
                }

                NuGetVersion semver = null;
                if (!NuGetVersion.TryParse(version, out semver))
                {
                    throw new PackagesConfigReaderException(string.Format(
                       CultureInfo.CurrentCulture,
                       Strings.ErrorInvalidPackageVersion,
                       id,
                       version));
                }

                string attributeValue = null;
                VersionRange allowedVersions = null;
                if (TryGetAttribute(package, "allowedVersions", out attributeValue))
                {
                    if (!VersionRange.TryParse(attributeValue, out allowedVersions))
                    {
                        throw new PackagesConfigReaderException(string.Format(
                            CultureInfo.CurrentCulture,
                            Strings.ErrorInvalidAllowedVersions,
                            id,
                            attributeValue));
                    }
                }

                var targetFramework = NuGetFramework.UnsupportedFramework;
                if (TryGetAttribute(package, "targetFramework", out attributeValue))
                {
                    targetFramework = NuGetFramework.Parse(attributeValue, _frameworkMappings);
                }

                var developmentDependency = BoolAttribute(package, "developmentDependency");
                var requireReinstallation = BoolAttribute(package, "requireReinstallation");
                var userInstalled = BoolAttribute(package, "userInstalled", true);

                var entry = new PackageReference(new PackageIdentity(id, semver), targetFramework, userInstalled, developmentDependency, requireReinstallation, allowedVersions);

                packages.Add(entry);
            }

            // check if there are duplicate entries
            var packageIds = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
            var duplicates = new List<string>();
            foreach (var package in packages)
            {
                if (packageIds.Contains(package.PackageIdentity.Id))
                {
                    duplicates.Add(package.PackageIdentity.Id);
                }
                else
                {
                    packageIds.Add(package.PackageIdentity.Id);
                }
            }

            if (duplicates.Count > 0)
            {
                throw new PackagesConfigReaderException(string.Format(
                    CultureInfo.CurrentCulture,
                    Strings.ErrorDuplicatePackages,
                    string.Join(", ", duplicates)));
            }

            return packages;
        }
		bool IsPackageVersionAllowed (IPackageSearchMetadata package, PackageReference packageReference)
		{
			if (!packageReference.HasAllowedVersions)
				return true;

			return packageReference.AllowedVersions.Satisfies (package.Identity.Version);
		}
		public override bool IsPackageInstalled (PackageReference reference)
		{
			return PackageReferencesWithPackageInstalled.Contains (reference);
		}
        private bool UpgradePackagesConfig(
      ProjectPackages oldPackagesConfig,
      ProjectFile project )
        {
            List<PackageReference> updatedPackages = new List<PackageReference>();

              bool changed = false;
              var logger = LogManager.GetCurrentClassLogger();

              foreach ( var package in oldPackagesConfig ) {
            var targetVersion = _packageIndex.GetTargetVersionOf( package.PackageIdentity.Id );

            PackageReference newPackage = new PackageReference(
              new PackageIdentity( package.PackageIdentity.Id, targetVersion ),
              package.TargetFramework,
              package.IsUserInstalled,
              package.IsDevelopmentDependency,
              package.RequireReinstallation,
              package.AllowedVersions );

            updatedPackages.Add( newPackage );

            if ( targetVersion.Equals( package.PackageIdentity.Version ) ) {
              continue;
            }

            changed = true;
            logger.Info( project.Name +
              ": Changing " + package.PackageIdentity.Id +
              " version " + package.PackageIdentity.Version + " to " + targetVersion );

            NuGetExtensions.InstallPackage( Path.GetDirectoryName( _projectFile ),  newPackage );
              }

              if ( !changed ) {
            return false;
              }

              var config = Path.Combine( Path.GetDirectoryName( _projectFile ), "packages.config" );
              logger.Info( "Writing changes to " + config );
              updatedPackages.Write( config );
              return true;
        }
 private ConfigitPackageReference( PackageReference reference )
 {
     _reference = reference;
 }
Ejemplo n.º 28
0
        /// <summary>
        /// Remove a package identity from the file
        /// </summary>
        /// <param name="identity">Package identity</param>
        /// <param name="targetFramework">Package targetFramework</param>
        public void RemovePackageEntry(PackageIdentity identity, NuGetFramework targetFramework)
        {
            var entry = new PackageReference(identity, targetFramework);

            RemovePackageEntry(entry);
        }
		PackageReferenceNode CreatePackageReferenceNode (PackageReference reference, UpdatedNuGetPackagesInProject updatedPackages)
		{
			// Floating package references (e.g. 1.0.1-*) are shown as installed.
			// Currently the version being used can be found in the project.lock.json but
			// reading this is not currently supported. So for now the package is shown
			// as installed since without the full version it is not possible to check
			// the NuGet package exists.
			bool installed = reference.IsFloating () || IsPackageInstalled (reference);

			return new PackageReferenceNode (
				this,
				reference,
				installed,
				false,
				updatedPackages.GetUpdatedPackage (reference.PackageIdentity.Id));
		}
		public virtual bool IsPackageInstalled (PackageReference reference)
		{
			if (IsNuGetIntegratedProject ()) {
				string path = packagePathResolver.GetHashPath (reference.PackageIdentity.Id, reference.PackageIdentity.Version);
				return File.Exists (path);
			}

			return folder.PackageExists (reference.PackageIdentity);
		}
        private async Task<IEnumerable<NuGetProjectAction>> PreviewUninstallPackageAsyncPrivate(NuGetProject nuGetProject, PackageReference packageReference,
            UninstallationContext uninstallationContext, INuGetProjectContext nuGetProjectContext, CancellationToken token)
        {
            if(SolutionManager == null)
            {
                throw new InvalidOperationException(Strings.SolutionManagerNotAvailableForUninstall);
            }

            if (nuGetProject is ProjectManagement.Projects.ProjectKNuGetProjectBase)
            {
                var action = NuGetProjectAction.CreateUninstallProjectAction(packageReference.PackageIdentity);
                return new NuGetProjectAction[] { action };
            }

            // Step-1 : Get the metadata resources from "packages" folder or custom repository path
            var packageIdentity = packageReference.PackageIdentity;
            var packageReferenceTargetFramework = packageReference.TargetFramework;
            nuGetProjectContext.Log(MessageLevel.Info, Strings.AttemptingToGatherDependencyInfo, packageIdentity, packageReferenceTargetFramework);

            // TODO: IncludePrerelease is a big question mark
            var installedPackageIdentities = (await nuGetProject.GetInstalledPackagesAsync(token)).Select(pr => pr.PackageIdentity);
            var dependencyInfoFromPackagesFolder = await GetDependencyInfoFromPackagesFolder(installedPackageIdentities,
                packageReferenceTargetFramework, includePrerelease: true);

            nuGetProjectContext.Log(MessageLevel.Info, Strings.ResolvingActionsToUninstallPackage, packageIdentity);
            // Step-2 : Determine if the package can be uninstalled based on the metadata resources
            var packagesToBeUninstalled = UninstallResolver.GetPackagesToBeUninstalled(packageIdentity, dependencyInfoFromPackagesFolder, installedPackageIdentities, uninstallationContext);

            var nuGetProjectActions = packagesToBeUninstalled.Select(p => NuGetProjectAction.CreateUninstallProjectAction(p));

            nuGetProjectContext.Log(MessageLevel.Info, Strings.ResolvedActionsToUninstallPackage, packageIdentity);
            return nuGetProjectActions;
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Reads all package node entries in the config.
        /// </summary>
        /// <param name="allowDuplicatePackageIds">If True validation will be performed to ensure that
        /// only one entry exists for each unique package id.</param>
        public IEnumerable <PackageReference> GetPackages(bool allowDuplicatePackageIds)
        {
            var packages = new List <PackageReference>();

            foreach (var package in _doc.Root.Elements(XName.Get(PackagesConfig.PackageNodeName)))
            {
                string id = null;
                if (!PackagesConfig.TryGetAttribute(package, "id", out id) ||
                    String.IsNullOrEmpty(id))
                {
                    throw new PackagesConfigReaderException(string.Format(
                                                                CultureInfo.CurrentCulture,
                                                                Strings.ErrorNullOrEmptyPackageId));
                }

                string version = null;
                if (!PackagesConfig.TryGetAttribute(package, PackagesConfig.VersionAttributeName, out version) ||
                    String.IsNullOrEmpty(version))
                {
                    throw new PackagesConfigReaderException(string.Format(
                                                                CultureInfo.CurrentCulture,
                                                                Strings.ErrorInvalidPackageVersion,
                                                                id,
                                                                version));
                }

                NuGetVersion semver = null;
                if (!NuGetVersion.TryParse(version, out semver))
                {
                    throw new PackagesConfigReaderException(string.Format(
                                                                CultureInfo.CurrentCulture,
                                                                Strings.ErrorInvalidPackageVersion,
                                                                id,
                                                                version));
                }

                string       attributeValue  = null;
                VersionRange allowedVersions = null;
                if (PackagesConfig.TryGetAttribute(package, PackagesConfig.allowedVersionsAttributeName, out attributeValue))
                {
                    if (!VersionRange.TryParse(attributeValue, out allowedVersions))
                    {
                        throw new PackagesConfigReaderException(string.Format(
                                                                    CultureInfo.CurrentCulture,
                                                                    Strings.ErrorInvalidAllowedVersions,
                                                                    id,
                                                                    attributeValue));
                    }
                }

                var targetFramework = NuGetFramework.UnsupportedFramework;
                if (PackagesConfig.TryGetAttribute(package, PackagesConfig.TargetFrameworkAttributeName, out attributeValue))
                {
                    targetFramework = NuGetFramework.Parse(attributeValue, _frameworkMappings);
                }

                var developmentDependency = PackagesConfig.BoolAttribute(package, PackagesConfig.developmentDependencyAttributeName);
                var requireReinstallation = PackagesConfig.BoolAttribute(package, PackagesConfig.RequireInstallAttributeName);
                var userInstalled         = PackagesConfig.BoolAttribute(package, PackagesConfig.UserInstalledAttributeName, true);

                var entry = new PackageReference(new PackageIdentity(id, semver), targetFramework, userInstalled, developmentDependency, requireReinstallation, allowedVersions);

                packages.Add(entry);
            }

            // check if there are duplicate entries
            var             duplicates   = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
            PackageIdentity lastIdentity = null;
            var             comparer     = PackageIdentity.Comparer;

            // Sort the list of packages and check for duplicates
            foreach (var package in packages.OrderBy(p => p.PackageIdentity, comparer))
            {
                if (lastIdentity != null)
                {
                    if (allowDuplicatePackageIds)
                    {
                        // Full compare
                        if (comparer.Equals(package.PackageIdentity, lastIdentity))
                        {
                            duplicates.Add(lastIdentity.ToString());
                        }
                    }
                    else if (string.Equals(
                                 package.PackageIdentity.Id,
                                 lastIdentity.Id,
                                 StringComparison.OrdinalIgnoreCase))
                    {
                        // Id only compare
                        duplicates.Add(lastIdentity.Id);
                    }
                }

                lastIdentity = package.PackageIdentity;
            }

            if (duplicates.Count > 0)
            {
                throw new PackagesConfigReaderException(string.Format(
                                                            CultureInfo.CurrentCulture,
                                                            Strings.ErrorDuplicatePackages,
                                                            string.Join(", ", duplicates)));
            }

            return(packages);
        }
        private Reference UpdateReference( string projectFolder, string relativePackageFolder,
                                       PackageIdentity oldPackage, PackageReference newestPackage, Reference reference )
        {
            var packageFolder = new DirectoryInfo(
            Path.GetFullPath( Path.Combine( projectFolder, relativePackageFolder, newestPackage.PackageIdentity.ToFolderName() ) ) );

              if ( !packageFolder.Exists ) {
            throw new Exception( "The package " + newestPackage.PackageIdentity + " failed to install?" );
              }
              var assemblyName = Path.GetFileName( reference.HintPath );

              Tuple<NuGetFramework, Reference> bestUpdate = null;

              foreach ( var file in packageFolder.GetFiles( assemblyName, SearchOption.AllDirectories ) ) {
            var updatedReference = TryUpdateReference( file.FullName, oldPackage, newestPackage, reference );

            if ( updatedReference == null ) {
              continue;
            }

            if ( updatedReference.Item1 == null ) {
              // If we don´t know the target framework we cannot pick the best
              // TODO: Get from assembly file itself?
              bestUpdate = updatedReference;
              break;
            }

            if ( bestUpdate == null || updatedReference.Item1.Equals( newestPackage.TargetFramework ) ) {
              bestUpdate = updatedReference;
            }
            else if ( StringComparer.OrdinalIgnoreCase.Compare(
              bestUpdate.Item1.GetShortFolderName(),
              newestPackage.TargetFramework.GetShortFolderName() ) <= 0 ) {
              bestUpdate = updatedReference;
            }
              }
              if ( bestUpdate != null ) {
            LogManager.GetCurrentClassLogger().Info( "Updated: " + reference + " to: " + bestUpdate.Item2 );
            return bestUpdate.Item2;
              }
              return null;
        }