Пример #1
0
        public void RoslynConfig_NoAnalyzerAssemblies_Succeeds()
        {
            // Arrange
            string            rootDir  = CreateTestFolders();
            TestLogger        logger   = new TestLogger();
            TeamBuildSettings settings = CreateSettings(rootDir);

            MockSonarQubeServer mockServer = CreateValidServer("valid.project", null, "valid.profile");
            QualityProfile      csProfile  = mockServer.Data.FindProfile("valid.profile", RoslynAnalyzerProvider.CSharpLanguage);

            csProfile.SetExport(RoslynAnalyzerProvider.RoslynCSharpFormatName, @"<?xml version=""1.0"" encoding=""utf-8""?>
<RoslynExportProfile Version=""1.0="">
  <Configuration>
    <RuleSet />
    <AdditionalFiles />
  </Configuration>
  <Deployment>
    <Plugins /> <!-- empty -->
  </Deployment>
</RoslynExportProfile>");

            RoslynAnalyzerProvider testSubject = CreateTestSubject(logger);

            // Act
            AnalyzerSettings actualSettings = testSubject.SetupAnalyzers(mockServer, settings, "valid.project", null);

            // Assert
            CheckSettingsInvariants(actualSettings);

            CheckExpectedAssemblies(actualSettings /* none */);

            logger.AssertErrorsLogged(0);
            logger.AssertWarningsLogged(0);
        }
Пример #2
0
        public void RoslynConfig_ValidRealSonarLintProfile()
        {
            // Arrange
            string            rootDir  = CreateTestFolders();
            TestLogger        logger   = new TestLogger();
            TeamBuildSettings settings = CreateSettings(rootDir);

            WellKnownProfile    testProfile = CreateRealSonarLintProfile();
            MockSonarQubeServer mockServer  = CreateServer("valid.project", null, "valid.profile", testProfile);

            RoslynAnalyzerProvider testSubject = CreateTestSubject(logger);

            // Act
            AnalyzerSettings actualSettings = testSubject.SetupAnalyzers(mockServer, settings, "valid.project", null);

            // Assert
            CheckSettingsInvariants(actualSettings);
            logger.AssertWarningsLogged(0);
            logger.AssertErrorsLogged(0);
            CheckRuleset(actualSettings, rootDir);
            CheckExpectedAdditionalFiles(testProfile, actualSettings);

            // Check the additional file is valid XML
            Assert.AreEqual(1, actualSettings.AdditionalFilePaths.Count(), "Test setup error: expecting only one additional file. Check the sample export XML has not changed");
            string filePath = actualSettings.AdditionalFilePaths.First();

            CheckFileIsXml(filePath);
        }
Пример #3
0
        public void RoslynConfig_ValidProfile()
        {
            // Arrange
            string            rootDir  = CreateTestFolders();
            TestLogger        logger   = new TestLogger();
            TeamBuildSettings settings = CreateSettings(rootDir);

            WellKnownProfile    testProfile = CreateValidCSharpProfile();
            MockSonarQubeServer mockServer  = CreateServer("valid.project", null, "valid.profile", testProfile);

            MockAnalyzerInstaller mockInstaller = new MockAnalyzerInstaller();

            mockInstaller.AssemblyPathsToReturn = new HashSet <string>(new string[] { "c:\\assembly1.dll", "d:\\foo\\assembly2.dll" });

            RoslynAnalyzerProvider testSubject = new RoslynAnalyzerProvider(mockInstaller, logger);

            // Act
            AnalyzerSettings actualSettings = testSubject.SetupAnalyzers(mockServer, settings, "valid.project", null);

            // Assert
            CheckSettingsInvariants(actualSettings);
            logger.AssertWarningsLogged(0);
            logger.AssertErrorsLogged(0);

            CheckRuleset(actualSettings, rootDir);
            CheckExpectedAdditionalFiles(testProfile, actualSettings);

            mockInstaller.AssertExpectedPluginsRequested(testProfile.Plugins);
            CheckExpectedAssemblies(actualSettings, "c:\\assembly1.dll", "d:\\foo\\assembly2.dll");
        }
Пример #4
0
        public void RoslynConfig_BranchMissingRuleset()
        {
            // This test is a regression scenario for SONARMSBRU-187:
            // We do not expect the project profile to be returned if we ask for a branch-specific profile

            // Arrange
            string            rootDir  = CreateTestFolders();
            TestLogger        logger   = new TestLogger();
            TeamBuildSettings settings = CreateSettings(rootDir);

            WellKnownProfile    testProfile = CreateValidCSharpProfile();
            MockSonarQubeServer mockServer  = CreateServer("valid.project", null, "valid.profile", testProfile);

            MockAnalyzerInstaller mockInstaller = new MockAnalyzerInstaller();

            mockInstaller.AssemblyPathsToReturn = new HashSet <string>(new string[] { "c:\\assembly1.dll", "d:\\foo\\assembly2.dll" });

            RoslynAnalyzerProvider testSubject = new RoslynAnalyzerProvider(mockInstaller, logger);

            // Act
            AnalyzerSettings actualSettings = testSubject.SetupAnalyzers(mockServer, settings, "valid.project", "missingBranch");

            // Assert
            AssertAnalyzerSetupNotPerformed(actualSettings, rootDir);

            logger.AssertErrorsLogged(0);
            logger.AssertWarningsLogged(0);
        }
Пример #5
0
        private TaskOutputs CreateLegacyProductProjectSettings(AnalyzerSettings settings)
        {
            var configOnlyAnalyzers = settings.AnalyzerPlugins.SelectMany(p => p.AssemblyPaths);
            var additionalFilePaths = MergeFileLists(settings.AdditionalFilePaths, OriginalAdditionalFiles);

            return(new TaskOutputs(settings.RulesetPath, configOnlyAnalyzers, additionalFilePaths));
        }
Пример #6
0
        private IncludeResolveStrategy CreateIncludeResolveStrategy()
        {
            string testDataDirectory = TestData.TestDataDirectory;

            Assert.IsNotNull(testDataDirectory);

            List <string> projectIncludeDirectories = new List <string>
            {
                Path.Combine(testDataDirectory, "DirA"),
                Path.Combine(testDataDirectory, "DirB")
            };

            List <string> interfaceIncludeDirectories = new List <string>
            {
                Path.Combine(testDataDirectory, "DirInterfaces")
            };

            List <string> externalIncludeDirectories = new List <string>
            {
                Path.Combine(testDataDirectory, "DirExternal")
            };

            AnalyzerSettings analyzerSettings         = AnalyzerSettings.CreateDefault();
            List <string>    systemIncludeDirectories = analyzerSettings.SystemIncludeDirectories;

            return(new IncludeResolveStrategy(projectIncludeDirectories, interfaceIncludeDirectories, externalIncludeDirectories, systemIncludeDirectories));
        }
        public void CheckBits1()
        {
            var tmpIniData           = DataHelper.LoadIni("");
            var tmpObjectInformation = new JavaLoader().CreateObjectInformation(new List <string> {
                JavaBits
            }, tmpIniData);
            var tmpAnalyerSettings    = new AnalyzerSettings();
            var tmpUnknownTypeCounter = 0;

            tmpAnalyerSettings.UnknownTypeAdded += (UnknownTypeClass inItem) => { tmpUnknownTypeCounter++; };
            new AnalyzerCore().LinkProjectInformation(tmpObjectInformation, tmpAnalyerSettings);

            new NamingConvertionHelper(new ConverterLucene()).ConvertProject(tmpObjectInformation);
            var tmpResult = CSharpWriter.CreateClassesFromObjectInformation(tmpObjectInformation, new ConverterLucene()).ToList();

            Assert.AreEqual(1, tmpResult.Count);
            Assert.AreEqual("Bits", tmpResult[0].FullName);
            //Check for inner classes existing

            //Expecting four unknown Types: true, false, int and boolean, two which I have not yet added a Pre-Runtime class
            Assert.AreEqual(0, tmpUnknownTypeCounter);

            Assert.AreEqual(true, tmpResult[0].Content.Contains("MatchAllBits"));

            Assert.AreEqual(true, tmpResult[0].Content.Contains("this.len = inLen;"));

            Assert.AreEqual(true, tmpResult[0].Content.Contains("Bits[] EMPTY_ARRAY =  new Bits[0];"));
        }
Пример #8
0
        public void AnalyzerSettingsTypeProperty_GetSet()
        {
            var instance = new AnalyzerSettings();

            instance.Type = "type";
            Assert.AreEqual("type", instance.Type);
        }
Пример #9
0
        public void AnalyzerSettingsWeightProperty_GetSet()
        {
            var instance = new AnalyzerSettings();

            instance.Weight = 3;
            Assert.AreEqual(3, instance.Weight);
        }
Пример #10
0
 public Analyzer(IDsiModel model, AnalyzerSettings analyzerSettings, IProgress <ProgressInfo> progress)
 {
     _model            = model;
     _analyzerSettings = analyzerSettings;
     _progress         = progress;
     _solutionFile     = new SolutionFile(analyzerSettings.InputFilename, _analyzerSettings, progress);
 }
Пример #11
0
        public void AnalyzerSettingsAliasProperty_GetSet()
        {
            var instance = new AnalyzerSettings();

            instance.Alias = "alias";
            Assert.AreEqual("alias", instance.Alias);
        }
Пример #12
0
        public override bool Execute()
        {
            bool taskSuccess = true;

            AnalysisConfig config = TaskUtilities.TryGetConfig(this.AnalysisConfigDir, new MSBuildLoggerAdapter(this.Log));

            if (config != null)
            {
                AnalyzerSettings settings = config.AnalyzerSettings;
                if (settings == null)
                {
                    this.Log.LogMessage(MessageImportance.Low, Resources.AnalyzerSettings_NotSpecifiedInConfig);
                }
                else
                {
                    this.RuleSetFilePath = settings.RuleSetFilePath;

                    if (settings.AnalyzerAssemblyPaths != null)
                    {
                        this.AnalyzerFilePaths = settings.AnalyzerAssemblyPaths.Where(f => IsAssemblyLibraryFileName(f)).ToArray();
                    }

                    if (settings.AdditionalFilePaths != null)
                    {
                        this.AdditionalFiles = settings.AdditionalFilePaths.ToArray();
                    }
                }
            }

            return(!this.Log.HasLoggedErrors && taskSuccess);
        }
        private void CheckRuleset(AnalyzerSettings actualSettings, string rootTestDir, string language)
        {
            string.IsNullOrWhiteSpace(actualSettings.RuleSetFilePath).Should().BeFalse("Ruleset file path should be set");
            Path.IsPathRooted(actualSettings.RuleSetFilePath).Should().BeTrue("Ruleset file path should be absolute");
            File.Exists(actualSettings.RuleSetFilePath).Should().BeTrue("Specified ruleset file does not exist: {0}", actualSettings.RuleSetFilePath);
            TestContext.AddResultFile(actualSettings.RuleSetFilePath);

            CheckFileIsXml(actualSettings.RuleSetFilePath);

            Path.GetFileName(actualSettings.RuleSetFilePath).Should().Be(RoslynAnalyzerProvider.GetRoslynRulesetFileName(language), "Ruleset file does not have the expected name");

            var expectedFilePath = GetExpectedRulesetFilePath(rootTestDir, language);

            actualSettings.RuleSetFilePath.Should().Be(expectedFilePath, "Ruleset was not written to the expected location");

            var expectedContent = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" Name=""Rules for SonarQube"" Description=""This rule set was automatically generated from SonarQube"" ToolsVersion=""14.0"">
  <Rules AnalyzerId=""SonarAnalyzer.CSharp"" RuleNamespace=""SonarAnalyzer.CSharp"">
    <Rule Id=""S1116"" Action=""Warning"" />
    <Rule Id=""S1125"" Action=""Warning"" />
    <Rule Id=""S1000"" Action=""None"" />
  </Rules>
  <Rules AnalyzerId=""Wintellect.Analyzers"" RuleNamespace=""Wintellect.Analyzers"">
    <Rule Id=""Wintellect003"" Action=""Warning"" />
  </Rules>
</RuleSet>";

            File.ReadAllText(actualSettings.RuleSetFilePath).Should().Be(expectedContent, "Ruleset file does not have the expected content: {0}", actualSettings.RuleSetFilePath);
        }
Пример #14
0
        public AnalyzerSettings SetupAnalyzer(TeamBuildSettings settings, IDictionary <string, string> serverSettings,
                                              IEnumerable <ActiveRule> activeRules, IEnumerable <string> inactiveRules, string language)
        {
            this.sqSettings       = settings ?? throw new ArgumentNullException(nameof(settings));
            this.sqServerSettings = serverSettings ?? throw new ArgumentNullException(nameof(serverSettings));
            if (language == null)
            {
                throw new ArgumentNullException(nameof(language));
            }

            if (inactiveRules == null)
            {
                throw new ArgumentNullException(nameof(inactiveRules));
            }
            if (activeRules == null)
            {
                throw new ArgumentNullException(nameof(activeRules));
            }
            if (!activeRules.Any())
            {
                return(null);
            }


            AnalyzerSettings analyzer = ConfigureAnalyzer(language, activeRules, inactiveRules);

            if (analyzer == null)
            {
                logger.LogInfo(Resources.RAP_NoPluginInstalled, language);
            }

            return(analyzer);
        }
Пример #15
0
        public void RoslynConfig_MissingRuleset()
        {
            // Arrange
            string            rootDir  = CreateTestFolders();
            TestLogger        logger   = new TestLogger();
            TeamBuildSettings settings = CreateSettings(rootDir);

            MockSonarQubeServer mockServer = CreateValidServer("valid.project", null, "valid.profile");
            QualityProfile      csProfile  = mockServer.Data.FindProfile("valid.profile", RoslynAnalyzerProvider.CSharpLanguage);

            csProfile.SetExport(RoslynAnalyzerProvider.RoslynCSharpFormatName, @"<?xml version=""1.0"" encoding=""utf-8""?>
<RoslynExportProfile Version=""1.0="">
  <Configuration>
    <!-- Missing ruleset -->
    <AdditionalFiles>
      <AdditionalFile FileName=""SonarLint.xml"" >
      </AdditionalFile>
    </AdditionalFiles>
  </Configuration>
  <Deployment />
</RoslynExportProfile>");

            RoslynAnalyzerProvider testSubject = CreateTestSubject(logger);

            // Act
            AnalyzerSettings actualSettings = testSubject.SetupAnalyzers(mockServer, settings, "valid.project", null);

            // Assert
            AssertAnalyzerSetupNotPerformed(actualSettings, rootDir);

            logger.AssertErrorsLogged(0);
            logger.AssertWarningsLogged(0);
        }
        private static void CompareAnalyzerSettings(IList <AnalyzerSettings> expectedList, IList <AnalyzerSettings> actualList)
        {
            Assert.IsNotNull(actualList, "Not expecting the AnalyzersSettings to be null for a reloaded file");

            if (expectedList == null)
            {
                Assert.IsTrue(actualList.Count == 0, "Expecting the reloaded analyzers settings to be empty");
                return;
            }

            Assert.IsNotNull(actualList, "Not expecting the actual analyzers settings to be null for a reloaded file");

            Assert.AreEqual(expectedList.Count, actualList.Count, "Expecting number of analyzer settings to be the same");

            for (int i = 0; i < actualList.Count; i++)
            {
                AnalyzerSettings actual   = actualList[i];
                AnalyzerSettings expected = expectedList[i];

                Assert.AreEqual(expected.RuleSetFilePath, actual.RuleSetFilePath, "Unexpected Ruleset value");

                CollectionAssert.AreEqual(expected.AnalyzerAssemblyPaths, actual.AnalyzerAssemblyPaths, "Analyzer assembly paths do not match");
                CollectionAssert.AreEqual(expected.AdditionalFilePaths, actual.AdditionalFilePaths, "Additional file paths do not match");
            }
        }
Пример #17
0
        private void FFRKViewInventory_Load(object sender, EventArgs e)
        {
            if (DesignMode)
            {
                return;
            }

            if (FFRKProxy.Instance != null)
            {
                mAnalyzerSettings = AnalyzerSettings.DefaultSettings;
                mAnalyzerSettings.LevelConsideration = TranslateLevelConsideration((ScoreUpgradeModeComboIndex)comboBoxScoreSelection.SelectedIndex);
                mAnalyzer = new EquipmentAnalyzer(mAnalyzerSettings);

                FFRKProxy.Instance.OnPartyList += FFRKProxy_OnPartyList;

                DataPartyDetails party = FFRKProxy.Instance.GameState.PartyDetails;
                if (party != null)
                {
                    // Run the initial analysis before updating the grids, so we can pass the
                    // scores straight through.  We'll run the analysis again every time they
                    // change one of the settings, so that the scores update on the fly.
                    mAnalyzer.Items   = party.Equipments;
                    mAnalyzer.Buddies = party.Buddies;
                    mAnalyzer.Run();
                    UpdatePartyGrid(party.Buddies.ToList());
                    UpdateEquipmentGrid(party.Equipments);
                }
            }
        }
Пример #18
0
 public Analyzer(IDsiModel model, AnalyzerSettings analyzerSettings, IProgress <ProgressInfo> progress)
 {
     _model            = model;
     _analyzerSettings = analyzerSettings;
     _progress         = progress;
     _repository       = new EA.Repository();
 }
Пример #19
0
        private string CreateMergedRuleset(AnalyzerSettings languageSpecificSettings)
        {
            // The original ruleset should have been provided to the task.
            // This should never be null when using the default targets
            // (if the user hasn't specified anything then it will be the
            // Microsoft minimum recommended tooleset).
            // However, we'll be defensive and handle nulls in case the
            // user has customised their build.
            if (OriginalRulesetFilePath == null)
            {
                // If the project doesn't already have a ruleset can just
                // return the generated one directly
                Log.LogMessage(MessageImportance.Low, Resources.AnalyzerSettings_OriginalRulesetNotSpecified, languageSpecificSettings.RuleSetFilePath);
                return(languageSpecificSettings.RuleSetFilePath);
            }

            string resolvedRulesetPath = GetAbsoluteRulesetPath();

            var mergedRulesetFilePath = Path.Combine(ProjectSpecificConfigDirectory, "merged.ruleset");

            Log.LogMessage(MessageImportance.Low, Resources.AnalyzerSettings_CreatingMergedRuleset, mergedRulesetFilePath);

            WriteMergedRuleSet(resolvedRulesetPath, languageSpecificSettings.RuleSetFilePath, mergedRulesetFilePath);
            return(mergedRulesetFilePath);
        }
        private void CheckExpectedAdditionalFiles(AnalyzerSettings actualSettings)
        {
            // Currently, only SonarLint.xml is written
            var filePaths = actualSettings.AdditionalFilePaths;

            filePaths.Should().ContainSingle();

            CheckExpectedAdditionalFileExists("SonarLint.xml", @"<?xml version=""1.0"" encoding=""UTF-8""?>
<AnalysisInput>
  <Settings>
  </Settings>
  <Rules>
    <Rule>
      <Key>S1116</Key>
      <Parameters>
        <Parameter>
          <Key>key</Key>
          <Value>value</Value>
        </Parameter>
      </Parameters>
    </Rule>
    <Rule>
      <Key>S1125</Key>
    </Rule>
  </Rules>
  <Files>
  </Files>
</AnalysisInput>
", actualSettings);
        }
Пример #21
0
        public void AnalyzerSettingsOptionsProperty_GetSet()
        {
            var instance = new AnalyzerSettings();

            instance.Options = new List <AnalyzerOption>();
            Assert.IsNotNull(instance.Options);
        }
Пример #22
0
        public void RoslynConfig_ValidProfile()
        {
            // Arrange
            string                rootFolder    = CreateTestFolders();
            TestLogger            logger        = new TestLogger();
            IList <ActiveRule>    activeRules   = createActiveRules();
            IList <string>        inactiveRules = createInactiveRules();
            string                language      = RoslynAnalyzerProvider.CSharpLanguage;
            MockAnalyzerInstaller mockInstaller = new MockAnalyzerInstaller();

            mockInstaller.AssemblyPathsToReturn = new HashSet <string>(new string[] { "c:\\assembly1.dll", "d:\\foo\\assembly2.dll" });
            TeamBuildSettings settings = CreateSettings(rootFolder);

            RoslynAnalyzerProvider testSubject = new RoslynAnalyzerProvider(mockInstaller, logger);

            // Act
            AnalyzerSettings actualSettings = testSubject.SetupAnalyzer(settings, ServerSettings, activeRules, inactiveRules, language);

            // Assert
            CheckSettingsInvariants(actualSettings);
            logger.AssertWarningsLogged(0);
            logger.AssertErrorsLogged(0);

            CheckRuleset(actualSettings, rootFolder, language);
            CheckExpectedAdditionalFiles(rootFolder, language, settings.SonarOutputDirectory, actualSettings);
            CheckExpectedAssemblies(actualSettings, "c:\\assembly1.dll", "d:\\foo\\assembly2.dll");
            List <string> plugins = new List <string>();

            plugins.Add("wintellect");
            plugins.Add("csharp");
            mockInstaller.AssertExpectedPluginsRequested(plugins);
        }
Пример #23
0
 public SolutionFile(string solutionPath, AnalyzerSettings analyzerSettings, IProgress <ProgressInfo> progress)
 {
     _solutionFileInfo = new FileInfo(solutionPath);
     _name             = _solutionFileInfo.Name;
     _analyzerSettings = analyzerSettings;
     _progress         = progress;
 }
Пример #24
0
        private void LoadSettings(string basePath)
        {
            if (!basePath.EndsWith(Path.DirectorySeparatorChar))
            {
                basePath += Path.DirectorySeparatorChar;
            }

            GeneralSettingsWrapper gsw = JsonConvert.DeserializeObject <GeneralSettingsWrapper>(File.ReadAllText(basePath + "settings.general.json"));

            _generalSettings = gsw.GeneralSettings;

            AnalyzerSettingsWrapper asw = JsonConvert.DeserializeObject <AnalyzerSettingsWrapper>(File.ReadAllText(basePath + "settings.analyzer.json"));

            _analyzerSettings = asw.AnalyzerSettings;

            if (!_generalSettings.Application.ProfitTrailerMonitorURL.EndsWith("/"))
            {
                _generalSettings.Application.ProfitTrailerMonitorURL += "/";
            }

            if (File.Exists(basePath + "settings.secure.json"))
            {
                SecureSettingsWrapper ssw = JsonConvert.DeserializeObject <SecureSettingsWrapper>(File.ReadAllText(basePath + "settings.secure.json"));
                _secureSettings = ssw.SecureSettings;
            }
        }
Пример #25
0
        static void Main(string[] args)
        {
            Logger.Init(Assembly.GetExecutingAssembly());

            if (args.Length < 1)
            {
                Logger.LogUserMessage("Usage: DsmSuite.Analyzer.Jdeps <settingsfile>");
            }
            else
            {
                FileInfo settingsFileInfo = new FileInfo(args[0]);
                if (!settingsFileInfo.Exists)
                {
                    AnalyzerSettings.WriteToFile(settingsFileInfo.FullName, AnalyzerSettings.CreateDefault());
                    Logger.LogUserMessage("Settings file does not exist. Default one created");
                }
                else
                {
                    AnalyzerSettings analyzerSettings = AnalyzerSettings.ReadFromFile(settingsFileInfo.FullName);
                    Logger.LoggingEnabled = analyzerSettings.LoggingEnabled;

                    ConsoleAction action = new ConsoleAction(analyzerSettings);
                    action.Execute();
                }
            }
        }
Пример #26
0
 public Analyzer(IDsiModel model, AnalyzerSettings analyzerSettings, IProgress <ProgressInfo> progress)
 {
     _model            = model;
     _analyzerSettings = analyzerSettings;
     _progress         = progress;
     _sourceDirectory  = new SourceDirectory(_analyzerSettings);
 }
        public void AnalysisConfGen_Simple()
        {
            // Arrange
            string analysisDir = TestUtils.CreateTestSpecificFolder(this.TestContext);

            TestLogger logger = new TestLogger();

            ListPropertiesProvider propertyProvider = new ListPropertiesProvider();

            propertyProvider.AddProperty(SonarProperties.HostUrl, "http://foo");
            ProcessedArgs args = new ProcessedArgs("valid.key", "valid.name", "1.0", false, EmptyPropertyProvider.Instance, propertyProvider);

            TeamBuildSettings tbSettings = TeamBuildSettings.CreateNonTeamBuildSettingsForTesting(analysisDir);

            Dictionary <string, string> serverSettings = new Dictionary <string, string>();

            serverSettings.Add("server.key.1", "server.value.1");

            AnalyzerSettings analyzerSettings = new AnalyzerSettings();

            analyzerSettings.RuleSetFilePath     = "c:\\xxx.ruleset";
            analyzerSettings.AdditionalFilePaths = new List <string>();
            analyzerSettings.AdditionalFilePaths.Add("f:\\additionalPath1.txt");
            analyzerSettings.AnalyzerAssemblyPaths = new List <string>();
            analyzerSettings.AnalyzerAssemblyPaths.Add("f:\\temp\\analyzer1.dll");

            List <AnalyzerSettings> analyzersSettings = new List <AnalyzerSettings>();

            analyzersSettings.Add(analyzerSettings);
            Directory.CreateDirectory(tbSettings.SonarConfigDirectory); // config directory needs to exist

            // Act
            AnalysisConfig actualConfig = AnalysisConfigGenerator.GenerateFile(args, tbSettings, serverSettings, analyzersSettings, logger);

            // Assert
            AssertConfigFileExists(actualConfig);
            logger.AssertErrorsLogged(0);
            logger.AssertWarningsLogged(0);

            Assert.AreEqual("valid.key", actualConfig.SonarProjectKey);
            Assert.AreEqual("valid.name", actualConfig.SonarProjectName);
            Assert.AreEqual("1.0", actualConfig.SonarProjectVersion);

            Assert.AreEqual("http://foo", actualConfig.SonarQubeHostUrl);

            Assert.AreEqual(tbSettings.SonarBinDirectory, actualConfig.SonarBinDir);
            Assert.AreEqual(tbSettings.SonarConfigDirectory, actualConfig.SonarConfigDir);
            Assert.AreEqual(tbSettings.SonarOutputDirectory, actualConfig.SonarOutputDir);
            Assert.AreEqual(tbSettings.SonarScannerWorkingDirectory, actualConfig.SonarScannerWorkingDirectory);
            Assert.AreEqual(tbSettings.BuildUri, actualConfig.GetBuildUri());
            Assert.AreEqual(tbSettings.TfsUri, actualConfig.GetTfsUri());

            Assert.IsNotNull(actualConfig.ServerSettings);
            Property serverProperty = actualConfig.ServerSettings.SingleOrDefault(s => string.Equals(s.Id, "server.key.1", System.StringComparison.Ordinal));

            Assert.IsNotNull(serverProperty);
            Assert.AreEqual("server.value.1", serverProperty.Value);
            Assert.AreSame(analyzerSettings, actualConfig.AnalyzersSettings[0]);
        }
        public void GetAnalyzerSettings_ConfigExists_DataReturned()
        {
            // Arrange
            var testDir     = TestUtils.CreateTestSpecificFolder(TestContext);
            var testSubject = new GetAnalyzerSettings();

            var expectedAnalyzers       = new string[] { "c:\\analyzer1.DLL", "c:\\analyzer2.dll" };
            var expectedAdditionalFiles = new string[] { "c:\\add1.txt", "d:\\add2.txt" };

            // SONARMSBRU-216: non-assembly files should be filtered out
            var filesInConfig = new List <string>(expectedAnalyzers)
            {
                "c:\\not_an_assembly.exe",
                "c:\\not_an_assembly.zip",
                "c:\\not_an_assembly.txt",
                "c:\\not_an_assembly.dll.foo",
                "c:\\not_an_assembly.winmd"
            };

            var config = new AnalysisConfig
            {
                AnalyzersSettings = new List <AnalyzerSettings>()
            };

            var settings = new AnalyzerSettings
            {
                Language              = "my lang",
                RuleSetFilePath       = "f:\\yyy.ruleset",
                AnalyzerAssemblyPaths = filesInConfig,
                AdditionalFilePaths   = expectedAdditionalFiles.ToList()
            };

            config.AnalyzersSettings.Add(settings);

            var anotherSettings = new AnalyzerSettings
            {
                Language              = "cobol",
                RuleSetFilePath       = "f:\\xxx.ruleset",
                AnalyzerAssemblyPaths = filesInConfig,
                AdditionalFilePaths   = expectedAdditionalFiles.ToList()
            };

            config.AnalyzersSettings.Add(anotherSettings);

            var fullPath = Path.Combine(testDir, FileConstants.ConfigFileName);

            config.Save(fullPath);

            testSubject.AnalysisConfigDir = testDir;
            testSubject.Language          = "my lang";

            // Act
            ExecuteAndCheckSuccess(testSubject);

            // Assert
            Assert.AreEqual("f:\\yyy.ruleset", testSubject.RuleSetFilePath);
            CollectionAssert.AreEquivalent(expectedAnalyzers, testSubject.AnalyzerFilePaths);
            CollectionAssert.AreEquivalent(expectedAdditionalFiles, testSubject.AdditionalFiles);
        }
Пример #29
0
        private TaskOutputs CreateMergedAnalyzerSettings(AnalyzerSettings settings)
        {
            var mergedRuleset       = CreateMergedRuleset(settings);
            var allAnalyzers        = MergeFileLists(settings.AnalyzerPlugins.SelectMany(ap => ap.AssemblyPaths), OriginalAnalyzers);
            var additionalFilePaths = MergeFileLists(settings.AdditionalFilePaths, OriginalAdditionalFiles);

            return(new TaskOutputs(mergedRuleset, allAnalyzers, additionalFilePaths));
        }
Пример #30
0
        private TaskOutputs CreateDeactivatedProjectSettings(AnalyzerSettings settings)
        {
            var sonarDotNetAnalyzers = settings.AnalyzerPlugins
                                       .Where(p => this.SonarDotNetPluginKeys.Contains(p.Key, StringComparer.OrdinalIgnoreCase))
                                       .SelectMany(p => p.AssemblyPaths);

            return(new TaskOutputs(settings.DeactivatedRulesetPath, sonarDotNetAnalyzers, settings.AdditionalFilePaths));
        }
Пример #31
0
        /// <summary>
        /// Process nested declarations.
        /// </summary>
        /// <param name="file">
        /// The <see cref="ICSharpFile"/> to use.
        /// </param>
        /// <param name="typeDeclarations">
        /// The type <see cref="ICSharpTypeDeclaration"/> to check.
        /// </param>
        /// <param name="analyzerSettings">
        /// The analyzer Settings.
        /// </param>
        private static void ProcessNestedTypeDeclarations(ICSharpFile file, IEnumerable<ITypeDeclaration> typeDeclarations, AnalyzerSettings analyzerSettings)
        {
            Param.RequireNotNull(file, "file");
            Param.RequireNotNull(typeDeclarations, "typeDeclarations");

            foreach (ITypeDeclaration typeDeclaration in typeDeclarations)
            {
                CheckDeclarationDocumentation(file, typeDeclaration, analyzerSettings);

                CheckClassDeclarationForParams(typeDeclaration, analyzerSettings);

                foreach (ITypeMemberDeclaration memberDeclaration in typeDeclaration.MemberDeclarations)
                {
                    CheckDeclarationDocumentation(file, memberDeclaration, analyzerSettings);
                }

                ProcessNestedTypeDeclarations(file, typeDeclaration.NestedTypeDeclarations, analyzerSettings);
            }
        }
Пример #32
0
        /// <summary>
        /// Inserts any missing items from the file header.
        /// Also formats the existing header ensuring that the top and bottom line start with 2 slashes and a space and that a newline follows the header.
        /// </summary>
        /// <param name="file">
        /// The file to update.
        /// </param>
        /// <param name="analyzerSettings">
        /// The analyzer Settings.
        /// </param>
        private static void UpdateFileHeader(ICSharpFile file, AnalyzerSettings analyzerSettings)
        {
            // The idea here is to load the existing header into our FileHeader object
            // The FileHeader object will ensure that the format of the header is correct even if we're not changing its contents
            // Thus we'll swap it out if its changed at the end.
            string fileName = file.GetSourceFile().ToProjectFile().Location.Name;

            // TODO: How do we handle updating the file header?
            // From the main options page?
            // Actually, looks like ReplaceCopyrightElement is the best option. It fixes the filename,
            // the company name and the copyright, and it'll update the summary, if it isn't already set.
            UpdateFileHeaderStyle updateFileHeaderOption = UpdateFileHeaderStyle.ReplaceCopyrightElement;

            if (updateFileHeaderOption == UpdateFileHeaderStyle.Ignore)
            {
                return;
            }

            Lifetimes.Using(
                lifetime =>
                    {
                        DocumentationRulesConfiguration docConfig = GetDocumentationRulesConfig(lifetime, file);
                        string summaryText = Utils.GetSummaryText(file);
                        FileHeader fileHeader = new FileHeader(file) { InsertSummary = analyzerSettings.IsRuleEnabled("FileHeaderMustHaveSummary") };

                        switch (updateFileHeaderOption)
                        {
                            case UpdateFileHeaderStyle.ReplaceCopyrightElement:
                                fileHeader.FileName = fileName;
                                fileHeader.CompanyName = docConfig.CompanyName;
                                fileHeader.CopyrightText = docConfig.Copyright;
                                fileHeader.Summary = string.IsNullOrEmpty(fileHeader.Summary) ? summaryText : fileHeader.Summary;
                                break;

                            case UpdateFileHeaderStyle.ReplaceAll:
                                fileHeader.FileName = fileName;
                                fileHeader.CompanyName = docConfig.CompanyName;
                                fileHeader.CopyrightText = docConfig.Copyright;
                                fileHeader.Summary = summaryText;
                                break;

                            case UpdateFileHeaderStyle.InsertMissing:
                                fileHeader.FileName = string.IsNullOrEmpty(fileHeader.FileName) ? fileName : fileHeader.FileName;
                                fileHeader.CompanyName = string.IsNullOrEmpty(fileHeader.CompanyName) ? docConfig.CompanyName : fileHeader.CompanyName;
                                fileHeader.CopyrightText = string.IsNullOrEmpty(fileHeader.CopyrightText) ? docConfig.Copyright : fileHeader.CopyrightText;
                                fileHeader.Summary = string.IsNullOrEmpty(fileHeader.Summary) ? summaryText : fileHeader.Summary;
                                break;
                        }

                        fileHeader.Update();
                    });
        }
Пример #33
0
        /// <summary>
        /// Checks declaration comment blocks.
        /// </summary>
        /// <param name="file">
        /// The <see cref="ICSharpFile"/> to use.
        /// </param>
        /// <param name="declaration">
        /// The <see cref="IDeclaration"/> to check.
        /// </param>s
        /// <param name="options">
        /// <see cref="AnalyzerSettings"/>Current options that we can reference.
        /// </param>
        public static void CheckDeclarationDocumentation(ICSharpFile file, IDeclaration declaration, AnalyzerSettings options)
        {
            Param.RequireNotNull(file, "file");
            Param.RequireNotNull(declaration, "declaration");
            Param.Ignore(options);

            bool insertMissingElementDocOption = options.IsRuleEnabled("ElementsMustBeDocumented");
            bool documentationTextMustBeginWithACapitalLetter = options.IsRuleEnabled("DocumentationTextMustBeginWithACapitalLetter");
            bool documentationTextMustEndWithAPeriod = options.IsRuleEnabled("DocumentationTextMustEndWithAPeriod");
            bool elementDocumentationMustHaveSummary = options.IsRuleEnabled("ElementDocumentationMustHaveSummary");
            bool constructorSummaryDocBeginsWithStandardText = options.IsRuleEnabled("ConstructorSummaryDocumentationMustBeginWithStandardText");
            bool destructorSummaryDocBeginsWithStandardText = options.IsRuleEnabled("DestructorSummaryDocumentationMustBeginWithStandardText");
            bool propertyDocumentationMustHaveValueDocumented = options.IsRuleEnabled("PropertyDocumentationMustHaveValue");
            bool insertMissingParamTagOption = options.IsRuleEnabled("ElementParametersMustBeDocumented");
            bool genericTypeParametersMustBeDocumented = options.IsRuleEnabled("GenericTypeParametersMustBeDocumented");

            DeclarationHeader declarationHeader = new DeclarationHeader(declaration);

            bool formatSummary = false;
            if (insertMissingElementDocOption && !Utils.IsRuleSuppressed(declaration, StyleCopRules.SA1600) && declarationHeader.IsMissing)
            {
                formatSummary = InsertMissingDeclarationHeader(file, declaration);
            }

            if (elementDocumentationMustHaveSummary && !Utils.IsRuleSuppressed(declaration, StyleCopRules.SA1604) && !declarationHeader.HasSummary)
            {
                formatSummary = formatSummary | InsertMissingSummaryElement(declaration);
            }

            if (formatSummary)
            {
                FormatSummaryElement(declaration);
            }

            if (declaration is IConstructorDeclaration)
            {
                if (insertMissingParamTagOption && !Utils.IsRuleSuppressed(declaration, StyleCopRules.SA1611))
                {
                    IConstructorDeclaration constructorDeclaration = declaration as IConstructorDeclaration;

                    if (constructorDeclaration.ParameterDeclarations.Count > 0)
                    {
                        InsertMissingParamElement(constructorDeclaration);
                    }
                }

                if (constructorSummaryDocBeginsWithStandardText && !Utils.IsRuleSuppressed(declaration, StyleCopRules.SA1642))
                {
                    EnsureConstructorSummaryDocBeginsWithStandardText(declaration as IConstructorDeclaration);
                }
            }

            Lifetimes.Using(
                lifetime =>
                    {
                        DocumentationRulesConfiguration docConfig = GetDocumentationRulesConfig(lifetime, file);

                        // However it can be on/off depending on the file so we'd have to cache it per file
                        bool ruleIsEnabled = docConfig.GetStyleCopRuleEnabled("DocumentationTextMustBeginWithACapitalLetter");

                        if (documentationTextMustBeginWithACapitalLetter && ruleIsEnabled && !Utils.IsRuleSuppressed(declaration, StyleCopRules.SA1628))
                        {
                            EnsureDocumentationTextIsUppercase(declaration);
                        }

                        ruleIsEnabled = docConfig.GetStyleCopRuleEnabled("DocumentationTextMustEndWithAPeriod");

                        if (documentationTextMustEndWithAPeriod && ruleIsEnabled && !Utils.IsRuleSuppressed(declaration, StyleCopRules.SA1629))
                        {
                            EnsureDocumentationTextEndsWithAPeriod(declaration);
                        }

                        if (declaration is IDestructorDeclaration)
                        {
                            if (destructorSummaryDocBeginsWithStandardText && !Utils.IsRuleSuppressed(declaration, StyleCopRules.SA1643))
                            {
                                EnsureDestructorSummaryDocBeginsWithStandardText(declaration as IDestructorDeclaration);
                            }
                        }

                        if (declaration is IMethodDeclaration || declaration is IIndexerDeclaration)
                        {
                            CheckMethodAndIndexerDeclarationDocumentation(declaration as IParametersOwnerDeclaration, options);
                        }

                        if (declaration is IPropertyDeclaration)
                        {
                            ruleIsEnabled = docConfig.GetStyleCopRuleEnabled("PropertyDocumentationMustHaveValue");

                            if (propertyDocumentationMustHaveValueDocumented && ruleIsEnabled && !Utils.IsRuleSuppressed(declaration, StyleCopRules.SA1609))
                            {
                                InsertValueElement(declaration as IPropertyDeclaration);
                            }
                        }

                        if (declaration is ITypeParametersOwner && (genericTypeParametersMustBeDocumented && !Utils.IsRuleSuppressed(declaration, StyleCopRules.SA1618)))
                        {
                            InsertMissingTypeParamElement(declaration);
                        }
                    });
        }
Пример #34
0
        /// <summary>
        /// The Execute method.
        /// </summary>
        /// <param name="file">
        /// The file to fix
        /// </param>
        /// <param name="settings">
        /// The settings to use in the fix.
        /// </param>
        public static void ExecuteAll(ICSharpFile file, Settings settings)
        {
            StyleCopTrace.In(file, settings);

            var analyzerSettings = new AnalyzerSettings(settings, typeof(CSharp.MaintainabilityRules).FullName);

            if (analyzerSettings.IsRuleEnabled("StatementMustNotUseUnnecessaryParenthesis"))
            {
                RemoveUnnecessaryParenthesisFromStatements(file.FirstChild);
            }

            StyleCopTrace.Out();
        }
Пример #35
0
        /// <summary>
        /// Processes the given element.
        /// </summary>
        /// <param name="element">The element being visited.</param>
        /// <param name="parentElement">The parent element, if any.</param>
        /// <param name="settings">The analyzer settings.</param>
        /// <returns>Returns true to continue, or false to stop the walker.</returns>
        private bool CheckDocumentationForElement(
            CsElement element,
            CsElement parentElement,
            AnalyzerSettings settings)
        {
            Param.AssertNotNull(element, "element");
            Param.Ignore(parentElement);
            Param.Ignore(settings);

            if (this.Cancel)
            {
                return false;
            }

            if (!element.Generated)
            {
                if (element.ElementType == ElementType.Class ||
                    element.ElementType == ElementType.Interface ||
                    element.ElementType == ElementType.Struct)
                {
                    ClassBase classElement = element as ClassBase;
                    Debug.Assert(classElement != null, "The element is not a class.");

                    this.CheckClassElementHeader(classElement, settings);
                }
                else if (element.ElementType == ElementType.Enum ||
                    element.ElementType == ElementType.Delegate ||
                    element.ElementType == ElementType.Event ||
                    element.ElementType == ElementType.Property ||
                    element.ElementType == ElementType.Indexer ||
                    element.ElementType == ElementType.Method ||
                    element.ElementType == ElementType.Constructor ||
                    element.ElementType == ElementType.Destructor ||
                    element.ElementType == ElementType.Field)
                {
                    this.CheckHeader(element, settings, false);
                }

                if (element.ElementType == ElementType.Enum)
                {
                    this.CheckEnumHeaders(element as Microsoft.StyleCop.CSharp.Enum, settings);
                }

                // Check the comments within the element, only for
                // elements which contain statements.
                if (element.ElementType == ElementType.Accessor ||
                    element.ElementType == ElementType.Constructor ||
                    element.ElementType == ElementType.Destructor ||
                    element.ElementType == ElementType.Method)
                {
                    this.CheckElementComments(element);
                }
            }

            return true;
        }
Пример #36
0
        /// <summary>
        /// Implement the Execute method.
        /// </summary>
        /// <param name="file">
        /// The file to use.
        /// </param>
        /// <param name="settings">
        /// The settings to use.
        /// </param>
        public static void ExecuteAll(ICSharpFile file, Settings settings)
        {
            StyleCopTrace.In(file, settings);

            var analyzerSettings = new AnalyzerSettings(settings, typeof(CSharp.SpacingRules).FullName);

            if (analyzerSettings.IsRuleEnabled("CodeMustNotContainMultipleWhitespaceInARow"))
            {
                CodeMustNotContainMultipleWhitespaceInARow(file.FirstChild);
            }

            if (analyzerSettings.IsRuleEnabled("CommasMustBeSpacedCorrectly"))
            {
                CommasMustBeSpacedCorrectly(file.FirstChild);
            }

            if (analyzerSettings.IsRuleEnabled("SingleLineCommentsMustBeginWithSingleSpace"))
            {
                SingleLineCommentsMustBeginWithSingleSpace(file.FirstChild);
            }

            if (analyzerSettings.IsRuleEnabled("PreprocessorKeywordsMustNotBePrecededBySpace"))
            {
                PreprocessorKeywordsMustNotBePrecededBySpace(file.FirstChild);
            }

            if (analyzerSettings.IsRuleEnabled("NegativeSignsMustBeSpacedCorrectly"))
            {
                NegativeAndPositiveSignsMustBeSpacedCorrectly(file.FirstChild, CSharpTokenType.MINUS);
            }

            if (analyzerSettings.IsRuleEnabled("PositiveSignsMustBeSpacedCorrectly"))
            {
                NegativeAndPositiveSignsMustBeSpacedCorrectly(file.FirstChild, CSharpTokenType.PLUS);
            }

            StyleCopTrace.Out();
        }
Пример #37
0
        /// <summary>
        /// Checks a class comments block for parameters.
        /// </summary>
        /// <param name="typeDeclaration">
        /// The <see cref="ITypeDeclaration"/> to check.
        /// </param>
        /// <param name="analyzerSettings">
        /// The <see cref="AnalyzerSettings"/> for the current analyzer.
        /// </param>
        private static void CheckClassDeclarationForParams(ITypeDeclaration typeDeclaration, AnalyzerSettings analyzerSettings)
        {
            Param.RequireNotNull(typeDeclaration, "typeDeclaration");
            Param.RequireNotNull(analyzerSettings, "analyzerSettings");

            if (analyzerSettings.IsRuleEnabled("ElementParametersMustBeDocumented"))
            {
                if (typeDeclaration.DeclaredElement != null)
                {
                    if (typeDeclaration.DeclaredElement.TypeParameters.Count > 0)
                    {
                        InsertMissingTypeParamElement(typeDeclaration);
                    }
                }
            }
        }
Пример #38
0
        /// <summary>
        /// Checks the Xml header block for consistency with the element it belongs to.
        /// </summary>
        /// <param name="element">The element to parse.</param>
        /// <param name="settings">The analyzer settings.</param>
        private void CheckEnumHeaders(Microsoft.StyleCop.CSharp.Enum element, AnalyzerSettings settings)
        {
            Param.AssertNotNull(element, "element");
            Param.Ignore(settings);

            foreach (EnumItem item in element.Items)
            {
                if (null == item.Header || item.Header.Text.Length == 0)
                {
                    if ((!settings.IgnorePrivates || element.Declaration.AccessModifierType != AccessModifierType.Private) &&
                        (!settings.IgnoreInternals || element.Declaration.AccessModifierType != AccessModifierType.Internal))
                    {
                        this.AddViolation(item, Rules.EnumerationItemsMustBeDocumented);
                    }
                }
                else
                {
                    this.ParseHeader(item, item.Header, item.LineNumber, false);
                }
            }
        }
Пример #39
0
        /// <summary>
        /// Checks the contents of the documentation for the elements in the document.
        /// </summary>
        /// <param name="document">The document to check.</param>
        private void CheckElementDocumentation(CsDocument document)
        {
            Param.AssertNotNull(document, "document");

            // Get the settings.
            AnalyzerSettings settings = new AnalyzerSettings();
            settings.IgnorePrivates = DocumentationRules.IgnorePrivatesDefaultValue;
            settings.IgnoreInternals = DocumentationRules.IgnoreInternalsDefaultValue;
            settings.RequireFields = DocumentationRules.IncludeFieldsDefaultValue;

            if (document.Settings != null)
            {
                BooleanProperty setting = document.Settings.GetAddInSetting(this, DocumentationRules.IgnorePrivates) as BooleanProperty;
                if (setting != null)
                {
                    settings.IgnorePrivates = setting.Value;
                }

                setting = document.Settings.GetAddInSetting(this, DocumentationRules.IgnoreInternals) as BooleanProperty;
                if (setting != null)
                {
                    settings.IgnoreInternals = setting.Value;
                }

                setting = document.Settings.GetAddInSetting(this, DocumentationRules.IncludeFieldsProperty) as BooleanProperty;
                if (setting != null)
                {
                    settings.RequireFields = setting.Value;
                }
            }

            ((CsDocument)document).WalkDocument<AnalyzerSettings>(
                new CodeWalkerElementVisitor<AnalyzerSettings>(this.CheckDocumentationForElement),
                settings);
        }
Пример #40
0
        /// <summary>
        /// The Execute method.
        /// </summary>
        /// <param name="file">
        /// The file to fix.
        /// </param>
        /// <param name="settings">
        /// The settings to use.
        /// </param>
        public static void ExecuteAll(ICSharpFile file, Settings settings)
        {
            StyleCopTrace.In(file, settings);

            var analyzerSettings = new AnalyzerSettings(settings, typeof(CSharp.LayoutRules).FullName);

            if (analyzerSettings.IsRuleEnabled("SingleLineCommentMustBeProceededByBlankLine"))
            {
                CommentsMustBePreceededByBlankLine(file.FirstChild);
            }

            if (analyzerSettings.IsRuleEnabled("SingleLineCommentsMustNotBeFollowedByBlankLine"))
            {
                CommentsMustNotBeFollowedByBlankLine(file.FirstChild);
            }

            if (analyzerSettings.IsRuleEnabled("ClosingCurlyBracketMustBeFollowedByBlankLine"))
            {
                ClosingCurlyBracketMustBeFollowedByBlankLine(file.FirstChild);
            }

            if (analyzerSettings.IsRuleEnabled("WhileDoFooterMustNotBePrecededByBlankLine"))
            {
                WhileDoFooterMustNotBePrecededByBlankLine(file.FirstChild);
            }

            if (analyzerSettings.IsRuleEnabled("ChainedStatementBlocksMustNotBePrecededByBlankLine"))
            {
                ChainedStatementBlocksMustNotBePrecededByBlankLine(file.FirstChild);
            }

            if (analyzerSettings.IsRuleEnabled("OpeningCurlyBracketsMustNotBePrecededByBlankLine"))
            {
                OpeningCurlyBracketsMustNotBePrecededByBlankLine(file.FirstChild);
            }

            if (analyzerSettings.IsRuleEnabled("ElementDocumentationHeaderMustBePrecededByBlankLine"))
            {
                ElementDocumentationHeadersMustBePrecededByBlankLine(file.FirstChild);
            }

            if (analyzerSettings.IsRuleEnabled("CurlyBracketsForMultiLineStatementsMustNotShareLine"))
            {
                CurlyBracketsForMultiLineStatementsMustNotShareLine(file.FirstChild);
            }

            StyleCopTrace.Out();
        }
Пример #41
0
        /// <summary>
        /// Checks the Xml header block for consistency with the element it belongs to.
        /// </summary>
        /// <param name="element">The element to parse.</param>
        /// <param name="settings">The analyzer settings.</param>
        private void CheckEnumHeaders(StyleCop.CSharp.CodeModel.Enum element, AnalyzerSettings settings)
        {
            Param.AssertNotNull(element, "element");
            Param.Ignore(settings);

            foreach (EnumItem item in element.Items)
            {
                ElementHeader header = item.Header;
                if (header == null || header.IsEmpty)
                {
                    if ((!settings.IgnorePrivates || element.AccessModifierType != AccessModifierType.Private) &&
                        (!settings.IgnoreInternals || element.AccessModifierType != AccessModifierType.Internal))
                    {
                        this.AddViolation(item, Rules.EnumerationItemsMustBeDocumented);
                    }
                }
                else
                {
                    this.ParseHeader(item, header, item.LineNumber, false);
                }
            }
        }
Пример #42
0
        /// <summary>
        /// Checks the contents of the documentation for the elements in the document.
        /// </summary>
        /// <param name="document">The document to check.</param>
        private void CheckElementDocumentation(CsDocument document)
        {
            Param.AssertNotNull(document, "document");

            // Get the settings.
            AnalyzerSettings settings = new AnalyzerSettings();
            settings.IgnorePrivates = DocumentationRules.IgnorePrivatesDefaultValue;
            settings.IgnoreInternals = DocumentationRules.IgnoreInternalsDefaultValue;
            settings.RequireFields = DocumentationRules.IncludeFieldsDefaultValue;

            BooleanProperty setting = this.GetSetting(document, DocumentationRules.IgnorePrivates) as BooleanProperty;
            if (setting != null)
            {
                settings.IgnorePrivates = setting.Value;
            }

            setting = this.GetSetting(document, DocumentationRules.IgnoreInternals) as BooleanProperty;
            if (setting != null)
            {
                settings.IgnoreInternals = setting.Value;
            }

            setting = this.GetSetting(document, DocumentationRules.IncludeFieldsProperty) as BooleanProperty;
            if (setting != null)
            {
                settings.RequireFields = setting.Value;
            }

            for (Element element = document.FindFirstDescendentElement(); element != null; element = element.FindNextDescendentElementOf(document))
            {
                if (this.Cancel)
                {
                    break;
                }

                this.CheckDocumentationForElement(element, settings);
            }
        }
        private static void CompareAnalyzerSettings(AnalyzerSettings expected, AnalyzerSettings actual)
        {
            if (expected == null)
            {
                Assert.IsNull(actual, "Expecting the reloaded analyzer settings to be null");
                return;
            }

            Assert.IsNotNull(actual, "Not expecting the actual analyzer settings to be null for a reloaded file");

            Assert.AreEqual(expected.RuleSetFilePath, actual.RuleSetFilePath, "Unexpected Ruleset value");

            CollectionAssert.AreEqual(expected.AnalyzerAssemblyPaths, actual.AnalyzerAssemblyPaths, "Analyzer assembly paths do not match");
            CollectionAssert.AreEqual(expected.AdditionalFilePaths, actual.AdditionalFilePaths, "Additional file paths do not match");
        }
Пример #44
0
        /// <summary>
        /// Checks method comment blocks.
        /// </summary>
        /// <param name="methodDeclaration">
        /// The method <see cref="IDeclaration"/> to check.
        /// </param>
        /// <param name="options">
        /// The options.
        /// </param>
        private static void CheckMethodAndIndexerDeclarationDocumentation(IParametersOwnerDeclaration methodDeclaration, AnalyzerSettings options)
        {
            Param.Ignore(options);

            if (methodDeclaration == null)
            {
                return;
            }

            bool insertMissingParamTagOption = options.IsRuleEnabled("ElementParametersMustBeDocumented");
            bool insertMissingReturnTagOption = options.IsRuleEnabled("ElementReturnValueMustBeDocumented");
            bool removeReturnTagOnVoidElementsOption = options.IsRuleEnabled("VoidReturnValueMustNotBeDocumented");

            if (insertMissingParamTagOption && !Utils.IsRuleSuppressed(methodDeclaration, StyleCopRules.SA1611))
            {
                if (methodDeclaration.ParameterDeclarations.Count > 0)
                {
                    InsertMissingParamElement(methodDeclaration);
                }
            }

            if (methodDeclaration.DeclaredElement == null)
            {
                return;
            }

             DeclaredTypeFromCLRName declaredTypeFromClrName = methodDeclaration.DeclaredParametersOwner.ReturnType as DeclaredTypeFromCLRName;

            if (removeReturnTagOnVoidElementsOption && !Utils.IsRuleSuppressed(methodDeclaration, StyleCopRules.SA1617))
            {
                // Remove the <returns> if the return type is void
                if (declaredTypeFromClrName != null && declaredTypeFromClrName.GetClrName().FullName == "System.Void")
                {
                    RemoveReturnsElement(methodDeclaration as ITypeMemberDeclaration);
                }
            }

            if (insertMissingReturnTagOption && !Utils.IsRuleSuppressed(methodDeclaration, StyleCopRules.SA1615))
            {
                // Insert the <returns> if the return type is not void and it was missing
                if ((declaredTypeFromClrName != null && declaredTypeFromClrName.GetClrName().FullName != "System.Void") || declaredTypeFromClrName == null)
                {
                    InsertReturnsElement(methodDeclaration as ITypeMemberDeclaration, Utils.GetXmlPresentableName(methodDeclaration.DeclaredParametersOwner.ReturnType));
                }
            }
        }
Пример #45
0
        /// <summary>
        /// Checks the Xml header block for consistency with the element it belongs to.
        /// </summary>
        /// <param name="element">The element to parse.</param>
        /// <param name="settings">The analyzer settings.</param>
        /// <param name="partialElement">Indicates whether the element has the partial attribute.</param>
        private void CheckHeader(CsElement element, AnalyzerSettings settings, bool partialElement)
        {
            Param.AssertNotNull(element, "element");
            Param.Ignore(settings);
            Param.Ignore(partialElement);

            // See whether this element has a header at all.
            if (null == element.Header || element.Header.Text.Length == 0)
            {
                // Empty or missing header is a violation if:
                // 1. The element is a class, interface, or struct
                // 2. The element is a field and the RequireFields flag is set
                // 3. The element is not private, or the element is private but the IgnorePrivates flag is not set
                // 4. The element is not internal, or the element is internal but the IgnoreInternals flag is not set
                if ((element.ElementType == ElementType.Class || element.ElementType == ElementType.Interface || element.ElementType == ElementType.Struct) ||
                    ((settings.RequireFields || element.ElementType != ElementType.Field) &&
                     (!settings.IgnorePrivates || element.Declaration.AccessModifierType != AccessModifierType.Private) &&
                     (!settings.IgnoreInternals || element.Declaration.AccessModifierType != AccessModifierType.Internal)))
                {
                    if (partialElement)
                    {
                        this.AddViolation(element, Rules.PartialElementsMustBeDocumented, element.FriendlyTypeText);
                    }
                    else
                    {
                        // We do not require headers for non-public static extern methods.
                        if (!IsNonPublicStaticExternDllImport(element))
                        {
                            this.AddViolation(element, Rules.ElementsMustBeDocumented, element.FriendlyTypeText);
                        }
                    }
                }
            }
            else
            {
                this.ParseHeader(element, element.Header, element.LineNumber, partialElement);
            }
        }
Пример #46
0
        /// <summary>
        /// Checks the Xml header block of the given class for consistency with the class.
        /// </summary>
        /// <param name="classElement">The element to parse.</param>
        /// <param name="settings">The analyzer settings.</param>
        private void CheckClassElementHeader(ClassBase classElement, AnalyzerSettings settings)
        {
            Param.AssertNotNull(classElement, "classElement");
            Param.Ignore(settings);

            AnalyzerSettings adjustedSettings = settings;
            adjustedSettings.RequireFields = false;

            if (classElement.Declaration.ContainsModifier(CsTokenType.Partial))
            {
                // This is a partial element. Check for the possible partial element header types.
                this.CheckHeader(classElement, adjustedSettings, true);
            }
            else
            {
                // Just perform the regular set of checks on the header.
                this.CheckHeader(classElement, adjustedSettings, false);
            }
        }
Пример #47
0
        /// <summary>
        /// Checks the Xml header block of the given class for consistency with the class.
        /// </summary>
        /// <param name="classElement">
        /// The element to parse.
        /// </param>
        /// <param name="settings">
        /// The analyzer settings.
        /// </param>
        private void CheckClassElementHeader(ClassBase classElement, AnalyzerSettings settings)
        {
            Param.AssertNotNull(classElement, "classElement");
            Param.Ignore(settings);

            AnalyzerSettings adjustedSettings = settings;
            adjustedSettings.RequireFields = false;

            this.CheckHeader(classElement, adjustedSettings, classElement.Declaration.ContainsModifier(CsTokenType.Partial));
        }
Пример #48
0
        /// <summary>
        /// Executes the cleanup rules.
        /// </summary>
        /// <param name="file">
        ///     The file to process.
        /// </param>
        /// <param name="settings">
        /// The merged settings for the given file
        /// </param>
        public static void ExecuteAll(ICSharpFile file, Settings settings)
        {
            StyleCopTrace.In(file);

            var analyzerSettings = new AnalyzerSettings(settings, typeof(CSharp.ReadabilityRules).FullName);

            if (analyzerSettings.IsRuleEnabled("DoNotPlaceRegionsWithinElements"))
            {
                DoNotPlaceRegionsWithinElements(file.FirstChild);
            }

            if (analyzerSettings.IsRuleEnabled("BlockStatementsMustNotContainEmbeddedComments"))
            {
                BlockStatementsMustNotContainEmbeddedComments(file.FirstChild);
            }

            if (analyzerSettings.IsRuleEnabled("BlockStatementsMustNotContainEmbeddedRegions"))
            {
                BlockStatementsMustNotContainEmbeddedRegions(file.FirstChild);
            }

            if (analyzerSettings.IsRuleEnabled("CodeMustNotContainEmptyStatements"))
            {
                CodeMustNotContainEmptyStatements(file.FirstChild);
            }

            if (analyzerSettings.IsRuleEnabled("CodeMustNotContainEmptyRegions"))
            {
                CodeMustNotContainEmptyRegions(file.FirstChild);
            }

            if (analyzerSettings.IsRuleEnabled("UseStringEmptyForEmptyStrings"))
            {
                ReplaceEmptyStringsWithStringDotEmpty(file.FirstChild);
            }

            if (analyzerSettings.IsRuleEnabled("UseBuiltInTypeAlias"))
            {
                SwapToBuiltInTypeAlias(file.FirstChild);
            }

            if (analyzerSettings.IsRuleEnabled("CommentsMustContainText"))
            {
                RemoveEmptyComments(file.FirstChild);
            }

            if (analyzerSettings.IsRuleEnabled("DoNotPrefixCallsWithBaseUnlessLocalImplementationExists"))
            {
                DoNotPrefixCallsWithBaseUnlessLocalImplementationExists(file.FirstChild);
            }

            StyleCopTrace.Out();
        }