public override Task <ProjectPackages> GetInstalledAndTransitivePackagesAsync(CancellationToken token)
            {
                var transitivePackages = TransitivePackages.Select(p => new TransitivePackageReference(p));

                var projectPackages = new ProjectPackages(InstalledPackages.ToList(), transitivePackages.ToList());

                return(Task.FromResult(projectPackages));
            }
        public void PackageNameContainsNumbers()
        {
            ProjectPackages projectPackages = new ProjectPackages( new[] {
            new PackageReference( new PackageIdentity( "C.1V1", NuGetVersion.Parse( "1.2.3" ) ), NuGetFramework.Parse( "net45" ), false )
              } );

              Assert.That( projectPackages.IsPackageReferenced( new Reference( string.Empty, null, null, "C.1V1.1.2.3" ).HintPath ), Is.True );
              Assert.That( projectPackages.IsPackageReferenced( new Reference( string.Empty, null, null, "C.2V1.1.2.3" ).HintPath ), Is.False );
        }
Exemplo n.º 3
0
 public bool PassAudit()
 {
     return(MissingPackages.IsEmpty() &&
            ProjectPackages.IsEmpty() &&
            InconsistentPackages.IsEmpty() &&
            UnusedPackages.IsEmpty() &&
            SnapshotPackages.IsEmpty() &&
            MissingPackageReferences.IsEmpty() &&
            DuplicatePackageReferences.IsEmpty() &&
            BindingRedirectMismatchReferences.IsEmpty() &&
            BadProjectRefGuids.IsEmpty() &&
            IllegalNugetTargets.IsEmpty());
 }
        public async Task GetInstalledPackagesAsync_PackageReferenceProject_ReturnsTransitiveAsync()
        {
            // Arrange
            var projectGuid = Guid.NewGuid();

            var settings          = new Mock <ISettings>();
            var telemetryProvider = new Mock <INuGetTelemetryProvider>(MockBehavior.Strict);

            var installedPackages = new List <PackageReference>()
            {
                new PackageReference(new PackageIdentity("a", new NuGetVersion(1, 0, 0)), FrameworkConstants.CommonFrameworks.Net50)
            };
            var transitivePackages = new List <PackageReference>()
            {
                new PackageReference(new PackageIdentity("b", new NuGetVersion(1, 2, 3)), FrameworkConstants.CommonFrameworks.Net50)
            };
            var transitiveProjectPackages = transitivePackages.Select(p => new TransitivePackageReference(p)).ToList();
            var projectPackages           = new ProjectPackages(installedPackages, transitiveProjectPackages);
            var project = new TestPackageReferenceProject("ProjectA", @"src\ProjectA\Project.csproj", @"c:\path\to\src\ProjectA\ProjectA.csproj",
                                                          installedPackages, transitivePackages);

            var solutionManager = new Mock <IVsSolutionManager>();

            solutionManager.Setup(sm => sm.GetNuGetProjectAsync(projectGuid.ToString()))
            .Returns(() => Task.FromResult <NuGetProject>(project));

            // Act
            var target = new NuGetProjectService(solutionManager.Object, settings.Object, telemetryProvider.Object);
            InstalledPackagesResult actual = await target.GetInstalledPackagesAsync(projectGuid, CancellationToken.None);

            // Assert
            Assert.NotNull(actual);
            Assert.Equal(InstalledPackageResultStatus.Successful, actual.Status);

            NuGetInstalledPackage package = actual.Packages.FirstOrDefault(p => p.Id == "a");

            Assert.NotNull(package);
            Assert.True(package.DirectDependency);

            package = actual.Packages.FirstOrDefault(p => p.Id == "b");
            Assert.NotNull(package);
            Assert.False(package.DirectDependency);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Merges project files and references
        /// </summary>
        /// <param name="projectPackages">Nuget package information</param>
        /// <param name="baseDocument">The base project xml</param>
        /// <param name="localDocument">The local project xml</param>
        /// <param name="incomingDocument">The incoming project xml</param>
        /// <param name="filePath">The file containing the conflicts being merged</param>
        /// <returns>Returns the merged items</returns>
        public IEnumerable<Item> Merge(
      string filePath,
      ProjectPackages projectPackages,
      XDocument baseDocument,
      XDocument localDocument,
      XDocument incomingDocument )
        {
            var projFileName = Path.GetFileName( filePath );

              var localProj = CsProjParser.Parse( projFileName, localDocument );
              var theirProj = CsProjParser.Parse( projFileName, incomingDocument );
              var baseProj = CsProjParser.Parse( projFileName, baseDocument );

              var localRefs = localProj.GetItems<Reference>().ToList();
              var theirRefs = theirProj.GetItems<Reference>().ToList();
              var baseRefs = baseProj.GetItems<Reference>().ToList();

              localRefs.ForEach( r => r.ApplyIsResolveOption( projectPackages ) );
              theirRefs.ForEach( r => r.ApplyIsResolveOption( projectPackages ) );
              baseRefs.ForEach( r => r.ApplyIsResolveOption( projectPackages ) );

              var localProjectRefs = localProj.GetItemsDictionary<ProjectReference>();
              var theirProjectRefs = theirProj.GetItemsDictionary<ProjectReference>();
              var baseProjectRefs = baseProj.GetItemsDictionary<ProjectReference>();

              var localItems = localProj.GetItemsDictionary<RawItem>();
              var theirItems = theirProj.GetItemsDictionary<RawItem>();
              var baseItems = baseProj.GetItemsDictionary<RawItem>();

              var resolvedItems = MergeHelper<RawItem>.MergeAll(
            filePath, _operation, baseItems, localItems, theirItems, _itemResolver );
              var resolvedReferences = MergeReferences( filePath, baseRefs, localRefs, theirRefs );

              var resolvedProjectReferences = MergeHelper<ProjectReference>.MergeAll(
            filePath, _operation, baseProjectRefs, localProjectRefs, theirProjectRefs, _projectReferenceResolver );

              return resolvedItems.Cast<Item>().Concat( resolvedReferences ).Concat( resolvedProjectReferences );
        }
Exemplo n.º 6
0
        public override string ToString()
        {
            var sb = new StringBuilder();

            sb.AppendLine(RoslynProject.Name);

            UnusedPackages.ForEach(p => sb.AppendFormat("\t{0}\n", p));
            ProjectPackages.ForEach(p => sb.AppendFormat("\t{0}\n", p));
            MissingPackages.ForEach(p => sb.AppendFormat("\t{0}\n", p));
            MissingPackageReferences.ForEach(p => sb.AppendFormat("\t{0}\n", p));
            BindingRedirectMismatchReferences.ForEach(p => sb.AppendFormat("\t{0}\n", p));
            SnapshotPackages.ForEach(p => sb.AppendFormat("\t{0}\n", p));
            DuplicatePackageReferences.ForEach(p => sb.AppendFormat("\t{0}\n", p));
            BadProjectRefGuids.ForEach(p => sb.AppendFormat("\t{0}\n", p));
            IllegalNugetTargets.ForEach(p => sb.AppendFormat("\t{0}\n", p));

            if (InconsistentPackages != null)
            {
                InconsistentPackages.ForEach(p => sb.AppendFormat("\t{0}\n", p));
            }

            return(sb.ToString());
        }
Exemplo n.º 7
0
        private static void ProcessProjectFiles(
      CurrentOperation operation,
      string[] conflictPaths,
      DirectoryInfo folder,
      Logger logger,
      string rootFolder )
        {
            var merger = new ProjectMerger(
            operation,
            new UserConflictResolver<ProjectReference>( operation, repositoryRootDirectory: rootFolder ),
            new ReferenceConflictResolver( new UserConflictResolver<Reference>( operation, notResolveOptionText: PackageNotInstalledText, repositoryRootDirectory: rootFolder ) ),
            new UserConflictResolver<RawItem>( operation, repositoryRootDirectory: rootFolder ),
            new UserDuplicateResolver<Reference>( operation, notResolveOptionText: PackageNotInstalledText, repositoryRootDirectory: rootFolder ) );

              foreach ( var conflict in conflictPaths.Where( p => p.EndsWith( ".csproj" ) || p.EndsWith( ".fsproj" ) || p.EndsWith( ".xproj" )) ) {

            var fullConflictPath = Path.Combine( folder.FullName, conflict );
            logger.Info( $"{LogHelper.Header}{Environment.NewLine}Examining concurrent modification for {fullConflictPath}" );

            var baseContent = GitHelper.GetConflictContent( rootFolder, StageLevel.Ancestor, conflict );
            var localContent = GitHelper.GetConflictContent( rootFolder, StageLevel.Ours, conflict );
            var incomingContent = GitHelper.GetConflictContent( rootFolder, StageLevel.Theirs, conflict );

            var conflictFolder = Path.GetDirectoryName( Path.Combine( rootFolder, conflict ) );

            if ( conflictFolder == null ) {
              throw new Exception( "No conflict folder" );
            }

            if ( string.IsNullOrEmpty( localContent ) || string.IsNullOrEmpty( incomingContent ) ) {
              logger.Log( LogLevel.Info, $"Skipping '{conflict}' - no content on one side" );
              continue;
            }

            var localDocument = XDocument.Parse( localContent );
            var incomingDocument = XDocument.Parse( incomingContent );
            var baseDocument = XDocument.Parse( baseContent ?? "<?xml version=\"1.0\" encoding=\"utf - 8\"?><Project/>" );

            var resolved = false;

            try {
              var projectFolder = Path.Combine( folder.FullName, conflictFolder );

              var packagesConfigFilePath = ProjectPackages.GetPackagesConfigFilePath( projectFolder );
              var packagesConfig = ProjectPackages.TryLoadPackagesConfig( packagesConfigFilePath );
              if ( packagesConfig == null ) {
            continue;
              }

              var packageIndex = new ProjectPackages( projectFolder, NuGetExtensions.FindRelativePathOfPackagesFolder( projectFolder ), packagesConfig );

              Item[] items = merger.Merge(
              conflict,
              packageIndex,
              baseDocument,
              localDocument,
              incomingDocument ).ToArray();

              // Now remove everything we have handled, to check if we are done.
              ProjectFile.DeleteItems( localDocument );
              ProjectFile.DeleteItems( incomingDocument );
              ProjectFile.DeleteItems( baseDocument );

              ProjectFile.AddItems( baseDocument, items );
              ProjectFile.AddItems( localDocument, items );
              ProjectFile.AddItems( incomingDocument, items );

              XDocument resolvedDocument = null;

              var localXml = localDocument.ToString();
              var incomingXml = incomingDocument.ToString();
              var baseXml = baseDocument.ToString();

              // Check for any project file changes outside of the references and items.
              if ( localXml == incomingXml ) {
            resolvedDocument = localDocument;
              } else if ( baseXml == localXml ) {
            resolvedDocument = incomingDocument;
              } else if ( baseXml == incomingXml ) {
            resolvedDocument = localDocument;
              }

              if ( resolvedDocument != null ) {
            // We handled all the differences
            using ( var textWriter = new StreamWriter( fullConflictPath ) ) {
              SerialisationHelper.WriteXml( resolvedDocument, textWriter );
            }
            using ( var repository = new Repository( rootFolder ) ) {
              repository.Stage( conflict );
            }

            resolved = true;
              }
            }       catch ( MergeAbortException ) {
              logger.Log( LogLevel.Info, $"Project merge aborted for {conflict}" );
              continue;
            } catch ( UserQuitException ) {
              throw;
            } catch ( Exception exception ) {
              logger.Log( LogLevel.Error, exception, $"Project merge failed for {conflict}{Environment.NewLine}{exception}" );
            }

            if ( resolved ) {
              continue;
            }

              string userQuestionText = $"Could not resolve conflict: {conflict}{Environment.NewLine}Would you like to resolve the conflict with the mergetool?";
              var userQuestion = new UserQuestion<bool>( userQuestionText, UserQuestion<bool>.YesNoOptions() );

              if ( userQuestion.Resolve() ) {

            using ( var repository = new Repository( rootFolder ) ) {
              GitHelper.ResolveWithStandardMergetool(
                repository,
                fullConflictPath,
                baseDocument,
                localDocument,
                incomingDocument,
                logger,
                conflict );
            }
              }
            }
        }
 public static void ApplyIsResolveOption( this Reference reference, ProjectPackages projectPackages )
 {
     reference.IsResolveOption = !projectPackages.IsPackageReference( reference.HintPath ) ||
                            projectPackages.IsPackageReferenced( reference.HintPath );
 }
            public override Task <ProjectPackages> GetInstalledAndTransitivePackagesAsync(CancellationToken token)
            {
                var projectPackages = new ProjectPackages(_installedPackages, _transitivePackages);

                return(Task.FromResult(projectPackages));
            }
        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 newPackage = _packageIndex.GetTarget( package.PackageIdentity.Id );

            updatedPackages.Add( newPackage );

            var newVersion = newPackage.PackageIdentity.Version;

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

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

            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;
        }
        public void AlignReferences()
        {
            Logger logger = LogManager.GetCurrentClassLogger();

              var projectFolder = Path.GetDirectoryName( _projectFile );
              var packagesRelativePath = NuGetExtensions.FindRelativePathOfPackagesFolder( projectFolder );

              var oldXml = ProjectPackages.TryLoadPackagesConfig( projectFolder );
              if ( oldXml == null ) {
            return;
              }

              ProjectPackages oldPackagesConfig = new ProjectPackages( projectFolder, packagesRelativePath, oldXml );

              var projectPath = _projectFile;
              ProjectFile project;

              using ( var fs = new FileStream( projectPath, FileMode.Open ) ) {
            project = CsProjParser.Parse( Path.GetFileName( projectPath ), fs );
              }

              if ( !UpgradePackagesConfig( oldPackagesConfig, project ) ) {
            return;
              }

              var newXml = ProjectPackages.TryLoadPackagesConfig( projectFolder );
              if ( newXml == null ) {
            return;
              }

              // reparse packages
              ProjectPackages updatedPackagesConfig = new ProjectPackages( projectFolder, packagesRelativePath, newXml );

              bool changed = false;

              Dictionary<Item, Item> itemMap = new Dictionary<Item, Item>( new XmlComparer( oldXml.Root.Name.Namespace ) );

              foreach ( var itemGroup in project.ItemGroups ) {

            foreach ( var item in itemGroup.Items ) {
              if ( !( item is Reference ) ) {
            itemMap[item] = item;
            continue;
              }
              Reference reference = item as Reference;

              if ( !oldPackagesConfig.IsPackageReference( reference.HintPath ) ) {
            if ( itemMap.ContainsKey( item ) ) {
              logger.Error(
                $"{_projectFile} has duplicate entry\n{item.ToElement( XNamespace.None )}\nThis has been fixed automatically." );
            }
            itemMap.Add( item, item ); // we keep any non package references (ie System.Xml)
            continue;
              }

              var referencedInOldPackage = oldPackagesConfig.IsPackageReferenced( reference.HintPath );

              if ( !referencedInOldPackage
               && !updatedPackagesConfig.IsPackageReferenced( reference.HintPath ) ) {
            logger.Info( "Removing " + reference + " as package not listed in packages.config" );
            changed = true;
            continue; // remove reference
              }

              PackageIdentity refPackage = oldPackagesConfig.PackageIdentityFromHintPath( reference.HintPath );

              PackageReference newestPackage = updatedPackagesConfig[refPackage.Id];

              if ( !refPackage.Equals( newestPackage.PackageIdentity ) ) {
            if ( new VersionComparer( VersionComparison.Default ).Compare( refPackage.Version, newestPackage.PackageIdentity.Version ) > 0 ) {
              logger.Warn( "The installed version "
                + newestPackage.PackageIdentity.Version
                + "(that we are aligning to) of " + refPackage.Id + " is lower than the referenced package version " + refPackage.Version );
            }
            var updatedReference = UpdateReference( projectFolder, packagesRelativePath, refPackage, newestPackage, reference );
            if ( updatedReference != null ) {
              reference = updatedReference;
              changed = true;
            }
            else {
              logger.Error( "Could not reconstruct hintpath " + reference.HintPath + " original reference will not be changed" );
            }
              }

              itemMap.Add( item, reference );
            }
              }

              if ( !changed ) {
            logger.Info( "No changes made to " + _projectFile );
            return;
              }

              XDocument projectXml = XDocument.Load( _projectFile );

              projectXml = ReplaceItems( projectXml, itemMap );

              using ( var textWriter = new StreamWriter( _projectFile ) ) {
            logger.Info( "Writing " + _projectFile );
            projectXml.WriteXml( textWriter );
              }
        }
Exemplo n.º 12
0
 public void ApplyIsResolveOption( ProjectPackages projectPackages )
 {
     IsResolveOption = !projectPackages.IsPackageReference( this ) || projectPackages.IsPackageReferenced( this );
 }