Inheritance: INuGetPackageHandler
        public void RoslynPlugin_GenerateForDependencyAnalyzers_Succeeds()
        {
            // Arrange
            TestLogger logger = new TestLogger();
            string outputDir = TestUtils.CreateTestDirectory(this.TestContext, ".out");
            string dummyContentFile = TestUtils.CreateTextFile("dummy.txt", outputDir, "non-analyzer content file");

            // Create a valid analyzer package
            RoslynAnalyzer11.CSharpAnalyzer analyzer = new RoslynAnalyzer11.CSharpAnalyzer();

            string fakeRemoteNuGetDir = TestUtils.CreateTestDirectory(this.TestContext, ".fakeRemoteNuGet");
            IPackageManager fakeRemotePkgMgr = CreatePackageManager(fakeRemoteNuGetDir);
            IPackage child1 = AddPackage(fakeRemotePkgMgr, "Analyzer.Child1", "1.1.0", analyzer.GetType().Assembly.Location);
            IPackage child2 = AddPackage(fakeRemotePkgMgr, "Analyzer.Child2", "1.2.0", analyzer.GetType().Assembly.Location);
            IPackage targetPkg = AddPackage(fakeRemotePkgMgr, "Empty.Parent", "1.0.0", dummyContentFile, child1, child2);

            string localPackageDestination = TestUtils.CreateTestDirectory(this.TestContext, ".localpackages");

            // Act
            NuGetPackageHandler nuGetHandler = new NuGetPackageHandler(fakeRemotePkgMgr.LocalRepository, localPackageDestination, logger);
            AnalyzerPluginGenerator apg = new AnalyzerPluginGenerator(nuGetHandler, logger);
            ProcessedArgs args = new ProcessedArgs(targetPkg.Id, targetPkg.Version, "cs", null, false,
                true /* generate plugins for dependencies with analyzers*/, outputDir);
            bool result = apg.Generate(args);

            // Assert
            Assert.IsTrue(result);

            // Expecting one plugin per dependency with analyzers
            CheckJarGeneratedForPackage(outputDir, analyzer, child1);
            CheckJarGeneratedForPackage(outputDir, analyzer, child2);
            AssertJarsGenerated(outputDir, 2);
        }
        public void RoslynPlugin_GenerateForValidAnalyzer_Succeeds()
        {
            // Arrange
            TestLogger logger = new TestLogger();
            string outputDir = TestUtils.CreateTestDirectory(this.TestContext, ".out");
            PluginInspector inspector = CreatePluginInspector(logger);

            // Create a valid analyzer package
            ExampleAnalyzer1.CSharpAnalyzer analyzer = new ExampleAnalyzer1.CSharpAnalyzer();

            string packageId = "analyzer1.id1";
            string localNuGetDir = TestUtils.CreateTestDirectory(this.TestContext, ".localNuGet");
            IPackageManager localNuGetStore = CreatePackageManager(localNuGetDir);
            AddPackage(localNuGetStore, packageId, "1.0", analyzer.GetType().Assembly.Location);

            // Act
            NuGetPackageHandler nuGetHandler = new NuGetPackageHandler(localNuGetDir, logger);
            AnalyzerPluginGenerator apg = new AnalyzerPluginGenerator(nuGetHandler, logger);
            bool result = apg.Generate(new Roslyn.CommandLine.NuGetReference(packageId, new SemanticVersion("1.0")), "cs", null, outputDir);

            // Assert
            Assert.IsTrue(result);
            string jarFilePath = AssertPluginJarExists(outputDir);

            JarInfo jarInfo = inspector.GetPluginDescription(jarFilePath);

            if (jarInfo != null)
            {
                this.TestContext.AddResultFile(jarInfo.FileName);
            }

            Assert.IsNotNull(jarInfo, "Failed to process the generated jar successfully");

            AssertPropertyDefinitionExists(packageId + "_sarif.AnalyzerId", jarInfo);
            AssertPropertyDefinitionExists(packageId + "_sarif.RuleNamespace", jarInfo);
            AssertPropertyDefinitionExists(packageId + "_sarif.nuget.packageId", jarInfo);
            AssertPropertyDefinitionExists(packageId + "_sarif.nuget.packageVersion", jarInfo);

            JarInfo.RulesDefinition rulesDefn = AssertRulesDefinitionExists(jarInfo);
            AssertRepositoryIsValid(rulesDefn.Repository);

            AssertExpectedRulesExist(analyzer, rulesDefn.Repository);

            Assert.AreEqual(5, jarInfo.Extensions.Count, "Unexpected number of extensions");
        }
        static int Main(string[] args)
        {
            ConsoleLogger logger = new ConsoleLogger();
            Common.Utilities.LogAssemblyVersion(typeof(Program).Assembly, UIResources.AssemblyDescription, logger);
            
            ProcessedArgs processedArgs = ArgumentProcessor.TryProcessArguments(args, logger);

            bool success = false;
            if (processedArgs != null)
            {
                NuGetPackageHandler packageHandler = new NuGetPackageHandler(NuGetPackageSource, logger);
                AnalyzerPluginGenerator generator = new AnalyzerPluginGenerator(packageHandler, logger);
                success = generator.Generate(processedArgs.AnalyzerRef, processedArgs.Language, processedArgs.SqaleFilePath,
                    System.IO.Directory.GetCurrentDirectory());
            }

            return success ? SUCCESS_CODE : ERROR_CODE;
        }
        static int Main(string[] args)
        {
            ConsoleLogger logger = new ConsoleLogger();
            Utilities.LogAssemblyVersion(typeof(Program).Assembly, UIResources.AssemblyDescription, logger);
            
            ProcessedArgs processedArgs = ArgumentProcessor.TryProcessArguments(args, logger);

            bool success = false;
            if (processedArgs != null)
            {
                string exeDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
                ISettings nuGetSettings = NuGetRepositoryFactory.GetSettingsFromConfigFiles(exeDir);
                IPackageRepository repo = NuGetRepositoryFactory.CreateRepository(nuGetSettings, logger);
                string localNuGetCache = Utilities.CreateTempDirectory(".nuget");
                NuGetPackageHandler packageHandler = new NuGetPackageHandler(repo, localNuGetCache, logger);

                AnalyzerPluginGenerator generator = new AnalyzerPluginGenerator(packageHandler, logger);
                success = generator.Generate(processedArgs);
            }

            return success ? SUCCESS_CODE : ERROR_CODE;
        }
        static int Main(string[] args)
        {
            ConsoleLogger logger = new ConsoleLogger();

            Utilities.LogAssemblyVersion(typeof(Program).Assembly, UIResources.AssemblyDescription, logger);

            ProcessedArgs processedArgs = ArgumentProcessor.TryProcessArguments(args, logger);

            bool success = false;

            if (processedArgs != null)
            {
                string              exeDir          = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
                ISettings           nuGetSettings   = NuGetRepositoryFactory.GetSettingsFromConfigFiles(exeDir);
                IPackageRepository  repo            = NuGetRepositoryFactory.CreateRepository(nuGetSettings, logger);
                string              localNuGetCache = Utilities.CreateTempDirectory(".nuget");
                NuGetPackageHandler packageHandler  = new NuGetPackageHandler(repo, localNuGetCache, logger);

                AnalyzerPluginGenerator generator = new AnalyzerPluginGenerator(packageHandler, logger);
                success = generator.Generate(processedArgs);
            }

            return(success ? SUCCESS_CODE : ERROR_CODE);
        }
        public void RoslynPlugin_GenerateForValidAnalyzer_Succeeds()
        {
            // Arrange
            TestLogger logger = new TestLogger();
            string outputDir = TestUtils.CreateTestDirectory(this.TestContext, ".out");

            // Create a valid analyzer package
            RoslynAnalyzer11.CSharpAnalyzer analyzer = new RoslynAnalyzer11.CSharpAnalyzer();

            string packageId = "Analyzer1.Pkgid1"; // package id is not all lowercase
            string fakeRemoteNuGetDir = TestUtils.CreateTestDirectory(this.TestContext, ".fakeRemoteNuGet");
            IPackageManager fakeRemotePkgMgr = CreatePackageManager(fakeRemoteNuGetDir);
            IPackage analyzerPkg =  AddPackage(fakeRemotePkgMgr, packageId, "1.0.2", analyzer.GetType().Assembly.Location);

            string localPackageDestination = TestUtils.CreateTestDirectory(this.TestContext, ".localpackages");

            // Act
            NuGetPackageHandler nuGetHandler = new NuGetPackageHandler(fakeRemotePkgMgr.LocalRepository, localPackageDestination, logger);
            AnalyzerPluginGenerator apg = new AnalyzerPluginGenerator(nuGetHandler, logger);
            ProcessedArgs args = new ProcessedArgs(packageId, new SemanticVersion("1.0.2"), "cs", null, false, false, outputDir);
            bool result = apg.Generate(args);

            // Assert
            Assert.IsTrue(result);

            // Expecting one plugin per dependency with analyzers
            CheckJarGeneratedForPackage(outputDir, analyzer, analyzerPkg);
            AssertJarsGenerated(outputDir, 1);
        }
        public void RoslynPlugin_GenerateForValidAnalyzer_Succeeds()
        {
            // Arrange
            TestLogger logger = new TestLogger();
            string outputDir = TestUtils.CreateTestDirectory(this.TestContext, ".out");

            // Create a valid analyzer package
            RoslynAnalyzer11.CSharpAnalyzer analyzer = new RoslynAnalyzer11.CSharpAnalyzer();

            string packageId = "Analyzer1.Pkgid1"; // package id is not all lowercase
            string fakeRemoteNuGetDir = TestUtils.CreateTestDirectory(this.TestContext, ".fakeRemoteNuGet");
            IPackageManager fakeRemotePkgMgr = CreatePackageManager(fakeRemoteNuGetDir);
            IPackage analyzerPkg =  AddPackage(fakeRemotePkgMgr, packageId, "1.0.2", analyzer.GetType().Assembly.Location);

            string localPackageDestination = TestUtils.CreateTestDirectory(this.TestContext, ".localpackages");

            // Act
            NuGetPackageHandler nuGetHandler = new NuGetPackageHandler(fakeRemotePkgMgr.LocalRepository, localPackageDestination, logger);
            AnalyzerPluginGenerator apg = new AnalyzerPluginGenerator(nuGetHandler, logger);
            ProcessedArgs args = new ProcessedArgs(packageId, new SemanticVersion("1.0.2"), "cs", null, false, outputDir);
            bool result = apg.Generate(args);

            // Assert
            Assert.IsTrue(result);
            string jarFilePath = AssertPluginJarExists(outputDir);

            // Check the content of the files embedded in the jar
            ZipFileChecker jarChecker = new ZipFileChecker(this.TestContext, jarFilePath);


            // Check the contents of the embedded config file
            string embeddedConfigFile = jarChecker.AssertFileExists("org\\sonar\\plugins\\roslynsdk\\configuration.xml");
            RoslynSdkConfiguration config = RoslynSdkConfiguration.Load(embeddedConfigFile);

            // Check the config settings
            Assert.AreEqual("analyzer1pkgid1", config.PluginKeyDifferentiator, "Unexpected repository differentiator");
            Assert.AreEqual("roslyn.analyzer1.pkgid1.cs", config.RepositoryKey, "Unexpected repository key");
            Assert.AreEqual("cs", config.RepositoryLanguage, "Unexpected language");
            Assert.AreEqual("dummy title", config.RepositoryName, "Unexpected repository name");
            
            // Check for the expected property values required by the C# plugin
            // Property name prefixes should be lower case; the case of the value should be the same as the package id
            AssertExpectedPropertyDefinitionValue("analyzer1.pkgid1.cs.analyzerId", "Analyzer1.Pkgid1", config);
            AssertExpectedPropertyDefinitionValue("analyzer1.pkgid1.cs.ruleNamespace", "Analyzer1.Pkgid1", config);
            AssertExpectedPropertyDefinitionValue("analyzer1.pkgid1.cs.nuget.packageId", "Analyzer1.Pkgid1", config);
            AssertExpectedPropertyDefinitionValue("analyzer1.pkgid1.cs.nuget.packageVersion", "1.0.2", config);
            AssertExpectedPropertyDefinitionValue("analyzer1.pkgid1.cs.staticResourceName", "Analyzer1.Pkgid1.1.0.2.zip", config);
            AssertExpectedPropertyDefinitionValue("analyzer1.pkgid1.cs.pluginKey", "analyzer1pkgid1", config);
            AssertExpectedPropertyDefinitionValue("analyzer1.pkgid1.cs.pluginVersion", "1.0.2", config);

            // Check the contents of the manifest
            string actualManifestFilePath = jarChecker.AssertFileExists("META-INF\\MANIFEST.MF");
            string[] actualManifest = File.ReadAllLines(actualManifestFilePath);
            AssertExpectedManifestValue(WellKnownPluginProperties.Key, "analyzer1pkgid1", actualManifest);
            AssertExpectedManifestValue("Plugin-Key", "analyzer1pkgid1", actualManifest); // plugin-key should be lowercase and alphanumeric
            AssertPackagePropertiesInManifest(analyzerPkg, actualManifest);


            // Check the rules
            string actualRuleFilePath = jarChecker.AssertFileExists("." + config.RulesXmlResourcePath);
            AssertExpectedRulesExist(analyzer, actualRuleFilePath);

            // Now create another checker to check the contents of the zip file (strict check this time)
            CheckEmbeddedAnalyzerPayload(jarChecker, "static\\analyzer1.pkgid1.1.0.2.zip",
                /* zip file contents */
                "analyzers\\RoslynAnalyzer11.dll");
        }
        public bool Generate(NuGetReference analyzeRef, string sqaleFilePath)
        {
            // sqale file path is optional
            if (analyzeRef == null)
            {
                throw new ArgumentNullException("analyzeRef");
            }

            string baseDirectory = Path.Combine(
                Path.GetTempPath(),
                Assembly.GetEntryAssembly().GetName().Name);

            string nuGetDirectory = Path.Combine(baseDirectory, ".nuget");

            NuGetPackageHandler downloader = new NuGetPackageHandler(logger);

            IPackage package = downloader.FetchPackage(NuGetPackageSource, analyzeRef.PackageId, analyzeRef.Version, nuGetDirectory);

            if (package != null)
            {
                // TODO: support multiple languages
                string language = SupportedLanguages.CSharp;
                PluginManifest pluginDefn = CreatePluginDefinition(package);

                string outputDirectory = Path.Combine(baseDirectory, ".output", Guid.NewGuid().ToString());
                Directory.CreateDirectory(outputDirectory);

                string rulesFilePath = Path.Combine(outputDirectory, "rules.xml");

                // TODO: we shouldn't try to work out where the content files have been installed by NuGet.
                // Instead, we should use the methods on IPackage to locate the assemblies e.g. Package.GetFiles()
                string packageDirectory = Path.Combine(nuGetDirectory, package.Id + "." + package.Version.ToString());
                Debug.Assert(Directory.Exists(packageDirectory), "Expected package directory does not exist: {0}", packageDirectory);

                bool success = TryGenerateRulesFile(packageDirectory, nuGetDirectory, rulesFilePath);

                if (success)
                {
                    BuildPlugin(analyzeRef, sqaleFilePath, language, pluginDefn, rulesFilePath, outputDirectory, package);
                }
            }

            return package != null;
        }