private IEnumerable <PackageReference> GetDependencies(IPackage package, FrameworkName frameworkName)
        {
            IEnumerable <PackageDependencySet> dependencySet;

            if (VersionUtility.TryGetCompatibleItems(frameworkName, package.DependencySets, out dependencySet))
            {
                foreach (var set in dependencySet)
                {
                    foreach (var d in set.Dependencies)
                    {
                        var dependency = _repository.FindPackagesById(d.Id)
                                         .Where(d.VersionSpec.ToDelegate())
                                         .FirstOrDefault();
                        if (dependency != null)
                        {
                            yield return(new PackageReference
                            {
                                Name = dependency.Id,
                                Version = dependency.Version
                            });
                        }
                    }
                }
            }
        }
Exemple #2
0
        public void FindPackagesByIdFindPackagesMatchingExactId()
        {
            // Arrange
            string id             = "Test";
            var    repositoryRoot = CreatePackage(id, version: "1.2", packageFileName: "Test.1.2.nupkg");

            CreatePackage(id, version: "1.3", packageFileName: "Test.1.3.nupkg", rootDir: repositoryRoot);
            CreatePackage(id, version: "2.0.0.9200-alpha", packageFileName: "Test.2.0.0.9200.nupkg", rootDir: repositoryRoot);

            IPackageRepository repository = new LocalPackageRepository(repositoryRoot);

            // Act
            var packages = repository.FindPackagesById(id).ToList();

            // Assert
            foreach (var p in packages)
            {
                Assert.True(p is OptimizedZipPackage);
            }

            Assert.Equal(3, packages.Count);
            Assert.Equal("1.2", packages[0].Version.ToString());
            Assert.Equal("1.3", packages[1].Version.ToString());
            Assert.Equal("2.0.0.9200-alpha", packages[2].Version.ToString());
        }
Exemple #3
0
        public void FindPackagesByIdThrowsIfIdIsNullOrEmpty(string id)
        {
            // Arrange
            var repository = new LocalPackageRepository(Mock.Of <IPackagePathResolver>(), Mock.Of <IFileSystem>());

            // Act and Assert
            ExceptionAssert.ThrowsArgNullOrEmpty(() => repository.FindPackagesById(id), "packageId");
        }
Exemple #4
0
 public Task <IEnumerable <PackageInfo> > FindPackagesByIdAsync(string id)
 {
     return(Task.FromResult(_repository.FindPackagesById(id).Select(p => new PackageInfo
     {
         Id = p.Id,
         Version = p.Version
     })));
 }
Exemple #5
0
        public void FindPackagesByIdReturnsEmptySequenceIfNoPackagesWithSpecifiedIdAreFound()
        {
            // Arramge
            var fileSystem             = new MockFileSystem();
            var pathResolver           = new DefaultPackagePathResolver(fileSystem);
            var localPackageRepository = new LocalPackageRepository(pathResolver, fileSystem);

            // Act
            var packages = localPackageRepository.FindPackagesById("Foo");

            // Assert
            Assert.Empty(packages);
        }
Exemple #6
0
 private void PurgeOldVersions(LocalPackageRepository targetRepo, IPackage package)
 {
     foreach (var oldPackage in targetRepo.FindPackagesById(package.Id).Where(p => p.Version < package.Version))
     {
         try
         {
             var path = GetPackagePath(oldPackage);
             Trace.WriteLine(string.Format("Deleting package {0}", oldPackage.GetFullName()));
             File.Delete(path);
         }
         catch
         {
             // Ignore
         }
     }
 }
Exemple #7
0
        public void FindPackagesByUsesIdFromManifestToValidateIdMatches()
        {
            // Arrange
            string id             = "Test";
            var    repositoryRoot = CreatePackage(id, version: "1.2", packageFileName: "Test.1.2.nupkg");

            CreatePackage(id, version: "1.3", packageFileName: "TeST.1.3.nupkg", rootDir: repositoryRoot);
            CreatePackage("Blah", version: "2.0.0", packageFileName: "Test.2.0.0.nupkg", rootDir: repositoryRoot);

            IPackageRepository repository = new LocalPackageRepository(repositoryRoot);

            // Act
            var packages = repository.FindPackagesById(id).ToList();

            // Assert
            Assert.Equal(2, packages.Count);
            Assert.Equal("1.2", packages[0].Version.ToString());
            Assert.Equal("1.3", packages[1].Version.ToString());
        }
Exemple #8
0
        public void FindPackagesByIdIgnoresPackagesThatDoNotMatchId()
        {
            // Arrange
            string id             = "Test";
            var    repositoryRoot = CreatePackage(id, version: "1.2", packageFileName: "Test.1.2.nupkg");

            CreatePackage(id, version: "1.3", packageFileName: "TeST.1.3.nupkg", rootDir: repositoryRoot);
            CreatePackage(id, version: "2.0.0.9200-alpha", packageFileName: "TEst.2.0.0.9200.nupkg", rootDir: repositoryRoot);
            CreatePackage("Test2", version: "2.0", packageFileName: "Test2.2.0.nupkg", rootDir: repositoryRoot);
            File.WriteAllBytes(Path.Combine(repositoryRoot, "NotTest.1.0.nupkg"), new byte[0]);

            IPackageRepository repository = new LocalPackageRepository(repositoryRoot);

            // Act
            var packages = repository.FindPackagesById(id).ToList();

            // Assert
            Assert.Equal(3, packages.Count);
            Assert.Equal("1.2", packages[0].Version.ToString());
            Assert.Equal("1.3", packages[1].Version.ToString());
            Assert.Equal("2.0.0.9200-alpha", packages[2].Version.ToString());
        }
Exemple #9
0
        public static int Main(string[] args)
        {
            // TODO: Take a switch saying whether to use TeamCity logger

            // TODO: Show extraneous packages, exclusions, etc.

            // TODO: Get this from the command line
            var ignoreAssistanceMode = IgnoreAssistanceMode.None;

            ignoreAssistanceMode = IgnoreAssistanceMode.ShowNew;

            if (args.Length < 1 || args.Length > 2)
            {
                Console.WriteLine(@"USAGE: NuGetSuperBVT.exe c:\path\to\packages [c:\path\to\packages-to-scan.json]");
                return(ReturnBadArgs);
            }

            var logger = new PackageVerifierLogger();

            IDictionary <string, PackageSet> packageSets = null;

            if (args.Length >= 2)
            {
                string packagesToScanJsonFilePath = args[1];
                if (!File.Exists(packagesToScanJsonFilePath))
                {
                    logger.LogError("Couldn't find packages JSON file at {0}", packagesToScanJsonFilePath);
                    return(ReturnBadArgs);
                }

                string packagesToScanJsonFileContent = File.ReadAllText(packagesToScanJsonFilePath);

                packageSets = JsonConvert.DeserializeObject <IDictionary <string, PackageSet> >(packagesToScanJsonFileContent, new JsonSerializerSettings()
                {
                    MissingMemberHandling = MissingMemberHandling.Error
                });

                logger.LogInfo("Read {0} package set(s) from {1}", packageSets.Count, packagesToScanJsonFilePath);
            }

            var totalTimeStopWatch = Stopwatch.StartNew();

            var nupkgsPath = args[0];


            // TODO: Look this up using reflection or something
            var allRules = new IPackageVerifierRule[] {
                new AssemblyHasDocumentFileRule(),
                new AssemblyHasVersionAttributesRule(),
                new AssemblyHasServicingAttributeRule(),
                new AssemblyStrongNameRule(),
                new AuthenticodeSigningRule(),
                new PowerShellScriptIsSignedRule(),
                new RequiredPackageMetadataRule(),
                new SatellitePackageRule(),
                new StrictSemanticVersionValidationRule(),
            }.ToDictionary(t => t.GetType().Name, t => t);


            var localPackageRepo = new LocalPackageRepository(nupkgsPath);

            var numPackagesInRepo = localPackageRepo.GetPackages().Count();

            logger.LogInfo("Found {0} packages in {1}", numPackagesInRepo, nupkgsPath);

            var processedPackages = new HashSet <IPackage>();

            var totalErrors   = 0;
            var totalWarnings = 0;

            var ignoreAssistanceData = new Dictionary <string, IDictionary <string, IDictionary <string, string> > >(StringComparer.OrdinalIgnoreCase);

            foreach (var packageSet in packageSets)
            {
                logger.LogInfo("Processing package set '{0}' with {1} package(s)", packageSet.Key, packageSet.Value.Packages.Count);

                var packageSetRuleInfo = packageSet.Value.Rules;

                var packageSetRules = packageSetRuleInfo.Select(ruleId => allRules.Single(rule => string.Equals(rule.Key, ruleId, StringComparison.OrdinalIgnoreCase)).Value);

                var analyzer = new PackageAnalyzer();
                foreach (var ruleInstance in packageSetRules)
                {
                    analyzer.Rules.Add(ruleInstance);
                }

                IList <IssueIgnore> issuesToIgnore = GetIgnoresFromFile(packageSet.Value.Packages);

                var issueProcessor = new IssueProcessor(issuesToIgnore);


                foreach (var packageInfo in packageSet.Value.Packages)
                {
                    var packageId         = packageInfo.Key;
                    var packageIgnoreInfo = packageInfo.Value;

                    var packagesWithId = localPackageRepo.FindPackagesById(packageId);
                    if (!packagesWithId.Any())
                    {
                        logger.LogError("Couldn't find package '{0}' in the repo", packageId);
                        totalErrors++;
                        continue;
                    }
                    if (packagesWithId.Count() > 1)
                    {
                        logger.LogError("Found more than one package with id '{0}' in the repo", packageId);
                        totalErrors++;
                        continue;
                    }
                    var package = packagesWithId.Single();

                    var packageTimeStopWatch = Stopwatch.StartNew();
                    logger.LogInfo("Analyzing {0} ({1})", package.Id, package.Version);


                    var issues = analyzer.AnalyzePackage(localPackageRepo, package, logger).ToList();

                    var packageErrorsAndWarnings = ProcessPackageIssues(
                        ignoreAssistanceMode, logger, issueProcessor,
                        ignoreAssistanceData, package, issues);

                    totalErrors   += packageErrorsAndWarnings.Item1;
                    totalWarnings += packageErrorsAndWarnings.Item2;


                    packageTimeStopWatch.Stop();
                    logger.LogInfo("Took {0}ms", packageTimeStopWatch.ElapsedMilliseconds);
                    Console.WriteLine();

                    processedPackages.Add(package);
                }
            }

            var unprocessedPackages = localPackageRepo.GetPackages().Except(processedPackages);

            if (unprocessedPackages.Any())
            {
                logger.LogWarning("Found {0} unprocessed packages. Every package in the repo should be listed in exactly one package set. Running all rules on unlisted packages.", unprocessedPackages.Count());

                // For unprocessed packages we run all rules (because we have no idea what exactly to run)
                var analyzer = new PackageAnalyzer();
                foreach (var ruleInstance in allRules.Values)
                {
                    analyzer.Rules.Add(ruleInstance);
                }

                var issueProcessor = new IssueProcessor(issuesToIgnore: null);

                foreach (var unprocessedPackage in unprocessedPackages)
                {
                    logger.LogWarning("\tUnprocessed package: {0} ({1})", unprocessedPackage.Id, unprocessedPackage.Version);

                    var packageTimeStopWatch = Stopwatch.StartNew();
                    logger.LogInfo("Analyzing {0} ({1})", unprocessedPackage.Id, unprocessedPackage.Version);


                    var issues = analyzer.AnalyzePackage(localPackageRepo, unprocessedPackage, logger).ToList();

                    var packageErrorsAndWarnings = ProcessPackageIssues(
                        ignoreAssistanceMode, logger, issueProcessor,
                        ignoreAssistanceData, unprocessedPackage, issues);

                    totalErrors   += packageErrorsAndWarnings.Item1;
                    totalWarnings += packageErrorsAndWarnings.Item2;


                    packageTimeStopWatch.Stop();
                    logger.LogInfo("Took {0}ms", packageTimeStopWatch.ElapsedMilliseconds);
                    Console.WriteLine();
                }
            }


            if (ignoreAssistanceMode != IgnoreAssistanceMode.None)
            {
                Console.WriteLine("Showing JSON for ignore content:");
                Console.WriteLine(JsonConvert.SerializeObject(ignoreAssistanceData, Formatting.Indented));
                Console.WriteLine();
            }

            LogLevel errorLevel = LogLevel.Info;

            if (totalWarnings > 0)
            {
                errorLevel = LogLevel.Warning;
            }
            if (totalErrors > 0)
            {
                errorLevel = LogLevel.Error;
            }
            logger.Log(
                errorLevel,
                "SUMMARY: {0} error(s) and {1} warning(s) found",
                totalErrors, totalWarnings);

            totalTimeStopWatch.Stop();
            logger.LogInfo("Total took {0}ms", totalTimeStopWatch.ElapsedMilliseconds);

            Console.ReadLine();

            return((totalErrors + totalWarnings > 0) ? ReturnErrorsOrWarnings : ReturnOk);
        }
        public void FindPackagesByIdReturnsEmptySequenceIfNoPackagesWithSpecifiedIdAreFound()
        {
            // Arramge
            var fileSystem = new MockFileSystem();
            var pathResolver = new DefaultPackagePathResolver(fileSystem);
            var localPackageRepository = new LocalPackageRepository(pathResolver, fileSystem);

            // Act
            var packages = localPackageRepository.FindPackagesById("Foo");

            // Assert
            Assert.Empty(packages);
        }
        public void FindPackagesByIdThrowsIfIdIsNullOrEmpty(string id)
        {
            // Arrange
            var repository = new LocalPackageRepository(Mock.Of<IPackagePathResolver>(), Mock.Of<IFileSystem>());

            // Act and Assert
            ExceptionAssert.ThrowsArgNullOrEmpty(() => repository.FindPackagesById(id), "packageId");
        }
        public void FindPackagesByUsesIdFromManifestToValidateIdMatches()
        {
            // Arrange
            string id = "Test";
            var repositoryRoot = CreatePackage(id, version: "1.2", packageFileName: "Test.1.2.nupkg");
            CreatePackage(id, version: "1.3", packageFileName: "TeST.1.3.nupkg", rootDir: repositoryRoot);
            CreatePackage("Blah", version: "2.0.0", packageFileName: "Test.2.0.0.nupkg", rootDir: repositoryRoot);

            IPackageRepository repository = new LocalPackageRepository(repositoryRoot);

            // Act
            var packages = repository.FindPackagesById(id).ToList();

            // Assert
            Assert.Equal(2, packages.Count);
            Assert.Equal("1.2", packages[0].Version.ToString());
            Assert.Equal("1.3", packages[1].Version.ToString());
        }
        public void FindPackagesByIdIgnoresPackagesThatDoNotMatchId()
        {
            // Arrange
            string id = "Test";
            var repositoryRoot = CreatePackage(id, version: "1.2", packageFileName: "Test.1.2.nupkg");
            CreatePackage(id, version: "1.3", packageFileName: "TeST.1.3.nupkg", rootDir: repositoryRoot);
            CreatePackage(id, version: "2.0.0.9200-alpha", packageFileName: "TEst.2.0.0.9200.nupkg", rootDir: repositoryRoot);
            CreatePackage("Test2", version: "2.0", packageFileName: "Test2.2.0.nupkg", rootDir: repositoryRoot);
            File.WriteAllBytes(Path.Combine(repositoryRoot, "NotTest.1.0.nupkg"), new byte[0]);

            IPackageRepository repository = new LocalPackageRepository(repositoryRoot);

            // Act
            var packages = repository.FindPackagesById(id).ToList();

            // Assert
            Assert.Equal(3, packages.Count);
            Assert.Equal("1.2", packages[0].Version.ToString());
            Assert.Equal("1.3", packages[1].Version.ToString());
            Assert.Equal("2.0.0.9200-alpha", packages[2].Version.ToString());
        }
        public void FindPackagesByIdFindPackagesMatchingExactId()
        {
            // Arrange
            string id = "Test";
            var repositoryRoot = CreatePackage(id, version: "1.2", packageFileName: "Test.1.2.nupkg");
            CreatePackage(id, version: "1.3", packageFileName: "Test.1.3.nupkg", rootDir: repositoryRoot);
            CreatePackage(id, version: "2.0.0.9200-alpha", packageFileName: "Test.2.0.0.9200.nupkg", rootDir: repositoryRoot);

            IPackageRepository repository = new LocalPackageRepository(repositoryRoot);

            // Act
            var packages = repository.FindPackagesById(id).ToList();

            // Assert
            foreach (var p in packages)
            {
                Assert.True(p is OptimizedZipPackage);
            }

            Assert.Equal(3, packages.Count);
            Assert.Equal("1.2", packages[0].Version.ToString());
            Assert.Equal("1.3", packages[1].Version.ToString());
            Assert.Equal("2.0.0.9200-alpha", packages[2].Version.ToString());
        }