public MockObjectFactory(ISonarQubeServer server, ITargetsInstaller targetsInstaller, IAnalyzerProvider analyzerProvider, IRulesetGenerator rulesetGenerator)
 {
     this.server           = server;
     this.targetsInstaller = targetsInstaller;
     this.analyzerProvider = analyzerProvider;
     this.rulesetGenerator = rulesetGenerator;
 }
Example #2
0
        /// <summary>
        /// Sets up the client to run the SonarLint analyzer as part of the build
        /// i.e. creates the Rolsyn ruleset and provisions the analyzer assemblies
        /// </summary>
        public static void SetupAnalyzers(ISonarQubeServer server, TeamBuildSettings settings, string projectKey, ILogger logger)
        {
            if (server == null)
            {
                throw new ArgumentNullException("server");
            }
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }
            if (string.IsNullOrWhiteSpace(projectKey))
            {
                throw new ArgumentNullException("projectKey");
            }
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            if (IsCSharpPluginInstalled(server))
            {
                if (TryCreateRuleset(server, settings, projectKey, logger))
                {
                    FetchBinaries(server, settings, logger);
                }
            }
            else
            {
                logger.LogDebug(Resources.SLAP_CSharpPluginNotInstalled);
            }
        }
        public AnalysisProperties InstallBuildWrapper(ISonarQubeServer server, string binDirectory, string outputDirectory)
        {
            if (server == null)
            {
                throw new ArgumentNullException("server");
            }
            if (string.IsNullOrWhiteSpace(binDirectory))
            {
                throw new ArgumentNullException("binDirectory");
            }

            AnalysisProperties properties = new AnalysisProperties();

            if (IsCppPluginInstalled(server) &&
                FetchResourceFromServer(server, binDirectory))
            {
                string bwOutputDir = Path.Combine(outputDirectory, "bw");
                properties.Add(new Property() { Id = BuildWrapperOutputPropertyKey, Value = bwOutputDir });
            }
            else
            {
                this.logger.LogInfo(Resources.BW_CppPluginNotInstalled);
            }

            return properties;
        }
        /// <summary>
        /// Sets up the client to run the SonarLint analyzer as part of the build
        /// i.e. creates the Rolsyn ruleset and provisions the analyzer assemblies
        /// </summary>
        public static void SetupAnalyzers(ISonarQubeServer server, TeamBuildSettings settings, string projectKey, ILogger logger)
        {
            if (server == null)
            {
                throw new ArgumentNullException("server");
            }
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }
            if (string.IsNullOrWhiteSpace(projectKey))
            {
                throw new ArgumentNullException("projectKey");
            }
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            if (IsCSharpPluginInstalled(server))
            {
                if (TryCreateRuleset(server, settings, projectKey, logger))
                {
                    FetchBinaries(server, settings, logger);
                }
            }
            else
            {
                logger.LogDebug(Resources.SLAP_CSharpPluginNotInstalled);
            }
        }
 public MockObjectFactory(ISonarQubeServer server, ITargetsInstaller targetsInstaller, IAnalyzerProvider analyzerProvider, IBuildWrapperInstaller buildWrapperInstaller)
 {
     this.server = server;
     this.targetsInstaller = targetsInstaller;
     this.analyzerProvider = analyzerProvider;
     this.buildWrapperInstaller = buildWrapperInstaller;
 }
        public AnalyzerSettings SetupAnalyzers(ISonarQubeServer sqServer, TeamBuildSettings teamBuildSettings, string sqProjectKey)
        {
            if (sqServer == null)
            {
                throw new ArgumentNullException("server");
            }
            if (teamBuildSettings == null)
            {
                throw new ArgumentNullException("settings");
            }
            if (string.IsNullOrWhiteSpace(sqProjectKey))
            {
                throw new ArgumentNullException("projectKey");
            }

            if (!IsCSharpPluginInstalled(sqServer))
            {
                logger.LogDebug(Resources.SLAP_CSharpPluginNotInstalled);
                return null;
            }

            this.server = sqServer;
            this.settings = teamBuildSettings;
            this.projectKey = sqProjectKey;

            AnalyzerSettings analyzerSettings = null;

            RoslynExportProfile profile = TryGetRoslynConfigForProject();
            if (profile != null)
            {
                analyzerSettings = ProcessProfile(profile);
            }

            return analyzerSettings;
        }
        private static bool TryCreateRuleset(ISonarQubeServer server, TeamBuildSettings settings, string projectKey, ILogger logger)
        {
            logger.LogDebug(Resources.SLAP_FetchingSonarLintRuleset);

            string rulesetContent;
            string parametersContent;
            if (TryGetProfileExportForProject(server, projectKey, logger, out rulesetContent, out parametersContent))
            {
                if (IsValidRuleset(rulesetContent))
                {
                    string ruleSetFilePath = GetRulesetFilePath(settings);
                    logger.LogDebug(Resources.SLAP_SonarLintRulesetCreated, ruleSetFilePath);
                    File.WriteAllText(ruleSetFilePath, rulesetContent);

                    string parametersFilePath = GetParametersFilePath(settings);
                    logger.LogDebug(Resources.SLAP_SonarLintParametersCreated, parametersFilePath);
                    File.WriteAllText(parametersFilePath, parametersContent);

                    return true;
                }
                else
                {
                    logger.LogError(Resources.SLAP_InvalidRulesetReturned);
                }
            }
            return false;
        }
        private bool FetchResourceFromServer(ISonarQubeServer server, string targetDir)
        {
            this.logger.LogDebug(Resources.BW_DownloadingBuildWrapper);

            Directory.CreateDirectory(targetDir);

            bool success = server.TryDownloadEmbeddedFile(CppPluginKey, BuildWrapperStaticResourceName, targetDir);

            if (success)
            {
                string targetFilePath = Path.Combine(targetDir, BuildWrapperStaticResourceName);

                if (IsZipFile(targetFilePath))
                {
                    this.logger.LogDebug(Resources.MSG_ExtractingFiles, targetDir);
                    ZipFile.ExtractToDirectory(targetFilePath, targetDir);
                }
            }
            else
            {
                // We assume that the absence of the embedded zip means that an old
                // version of the Cpp plugin is installed
                this.logger.LogWarning(Resources.BW_CppPluginUpgradeRequired);
            }
            return success;
        }
        AnalyzerSettings IAnalyzerProvider.SetupAnalyzers(ISonarQubeServer server, TeamBuildSettings settings, string projectKey)
        {
            Assert.IsNotNull(server);
            Assert.IsNotNull(settings);
            Assert.IsFalse(string.IsNullOrWhiteSpace(projectKey));

            return this.SettingsToReturn;
        }
Example #10
0
        AnalyzerSettings IAnalyzerProvider.SetupAnalyzers(ISonarQubeServer server, TeamBuildSettings settings, string projectKey, string projectBranch)
        {
            Assert.IsNotNull(server);
            Assert.IsNotNull(settings);
            Assert.IsFalse(string.IsNullOrWhiteSpace(projectKey));
            // projectBranch can be null

            return(this.SettingsToReturn);
        }
        AnalysisProperties IBuildWrapperInstaller.InstallBuildWrapper(ISonarQubeServer server, string binDirectory, string outputDirectory)
        {
            Assert.IsNotNull(server, "Supplied server should not be null");
            Assert.IsFalse(string.IsNullOrWhiteSpace(binDirectory), "Supplied bin directory should not be null or empty");
            Assert.IsFalse(string.IsNullOrWhiteSpace(outputDirectory), "Supplied output directory should not be null or empty");

            this.callCount++;

            return new AnalysisProperties();
        }
        /// <summary>
        /// Retrieves settings from the SonarQube server and generates a an FxCop file on disc
        /// </summary>
        /// <param name="server">SonarQube server instance</param>
        /// <param name="requiredPluginKey">The plugin key that defines the given language</param>
        /// <param name="language">The language of the FxCop repository</param>
        /// <param name="fxCopRepositoryKey">The key of the FxCop repository</param>
        /// <param name="sonarProjectKey">The key of the SonarQube project for which the ruleset should be generated</param>
        /// <param name="sonarProjectBranch">The branch of the SonarQube project for which the ruleset should be generated (optional).</param>
        /// <param name="outputFilePath">The full path to the file to be generated</param>
        public static void Generate(ISonarQubeServer server, string requiredPluginKey, string language, string fxCopRepositoryKey, string sonarProjectKey, string sonarProjectBranch, string outputFilePath)
        {
            if (server == null)
            {
                throw new ArgumentNullException("server");
            }
            if (string.IsNullOrWhiteSpace(requiredPluginKey))
            {
                throw new ArgumentNullException("requiredPluginKey");
            }
            if (string.IsNullOrWhiteSpace(language))
            {
                throw new ArgumentNullException("language");
            }
            if (string.IsNullOrWhiteSpace(fxCopRepositoryKey))
            {
                throw new ArgumentNullException("fxCopRepositoryKey");
            }
            if (string.IsNullOrWhiteSpace(sonarProjectKey))
            {
                throw new ArgumentNullException("sonarProjectKey");
            }
            if (string.IsNullOrWhiteSpace(outputFilePath))
            {
                throw new ArgumentNullException("outputFilePath");
            }

            IEnumerable <string> activeRuleKeys = Enumerable.Empty <string>();

            if (server.GetInstalledPlugins().Contains(requiredPluginKey))
            {
                string qualityProfile;
                if (server.TryGetQualityProfile(sonarProjectKey, sonarProjectBranch, language, out qualityProfile))
                {
                    activeRuleKeys = server.GetActiveRuleKeys(qualityProfile, language, fxCopRepositoryKey);
                }
            }

            if (activeRuleKeys.Any())
            {
                var internalKeys = server.GetInternalKeys(fxCopRepositoryKey);
                var ids          = activeRuleKeys.Select(
                    k =>
                {
                    var fullKey = fxCopRepositoryKey + ':' + k;
                    return(internalKeys.ContainsKey(fullKey) ? internalKeys[fullKey] : k);
                });

                File.WriteAllText(outputFilePath, RulesetWriter.ToString(ids));
            }
            else
            {
                File.Delete(outputFilePath);
            }
        }
        /// <summary>
        /// Retrieves settings from the SonarQube server and generates a an FxCop file on disc
        /// </summary>
        /// <param name="server">SonarQube server instance</param>
        /// <param name="requiredPluginKey">The plugin key that defines the given language</param>
        /// <param name="language">The language of the FxCop repository</param>
        /// <param name="fxCopRepositoryKey">The key of the FxCop repository</param>
        /// <param name="sonarProjectKey">The key of the SonarQube project for which the ruleset should be generated</param>
        /// <param name="outputFilePath">The full path to the file to be generated</param>
        public static void Generate(ISonarQubeServer server, string requiredPluginKey, string language, string fxCopRepositoryKey, string sonarProjectKey, string outputFilePath)
        {
            if (server == null)
            {
                throw new ArgumentNullException("server");
            }
            if (string.IsNullOrWhiteSpace(requiredPluginKey))
            {
                throw new ArgumentNullException("requiredPluginKey");
            }
            if (string.IsNullOrWhiteSpace(language))
            {
                throw new ArgumentNullException("language");
            }
            if (string.IsNullOrWhiteSpace(fxCopRepositoryKey))
            {
                throw new ArgumentNullException("fxCopRepositoryKey");
            }
            if (string.IsNullOrWhiteSpace(sonarProjectKey))
            {
                throw new ArgumentNullException("sonarProjectKey");
            }
            if (string.IsNullOrWhiteSpace(outputFilePath))
            {
                throw new ArgumentNullException("outputFilePath");
            }

            IEnumerable<string> activeRuleKeys = Enumerable.Empty<string>();
            if (server.GetInstalledPlugins().Contains(requiredPluginKey))
            {
                string qualityProfile;
                if (server.TryGetQualityProfile(sonarProjectKey, language, out qualityProfile))
                {
                    activeRuleKeys = server.GetActiveRuleKeys(qualityProfile, language, fxCopRepositoryKey);
                }
            }

            if (activeRuleKeys.Any())
            {
                var internalKeys = server.GetInternalKeys(fxCopRepositoryKey);
                var ids = activeRuleKeys.Select(
                    k =>
                    {
                        var fullKey = fxCopRepositoryKey + ':' + k;
                        return internalKeys.ContainsKey(fullKey) ? internalKeys[fullKey] : k;
                    });

                File.WriteAllText(outputFilePath, RulesetWriter.ToString(ids));
            }
            else
            {
                File.Delete(outputFilePath);
            }
        }
Example #14
0
        public ISonarQubeServer CreateSonarQubeServer(ProcessedArgs args)
        {
            if (args == null)
            {
                throw new ArgumentNullException(nameof(args));
            }

            var username = args.GetSetting(SonarProperties.SonarUserName, null);
            var password = args.GetSetting(SonarProperties.SonarPassword, null);
            var hostUrl  = args.SonarQubeUrl;

            this.server = new SonarWebService(new WebClientDownloader(username, password, this.logger), hostUrl, this.logger);
            return(this.server);
        }
Example #15
0
        public EmbeddedAnalyzerInstaller(ISonarQubeServer server, string localCacheDirectory, ILogger logger)
        {
            if (string.IsNullOrWhiteSpace(localCacheDirectory))
            {
                throw new ArgumentNullException(nameof(localCacheDirectory));
            }

            this.server = server ?? throw new ArgumentNullException(nameof(server));
            this.logger = logger ?? throw new ArgumentNullException(nameof(logger));

            this.logger.LogDebug(RoslynResources.EAI_LocalAnalyzerCache, localCacheDirectory);
            Directory.CreateDirectory(localCacheDirectory); // ensure the cache dir exists

            cache = new PluginResourceCache(localCacheDirectory);
        }
Example #16
0
        private bool FetchArgumentsAndRulesets(ProcessedArgs args, TeamBuildSettings settings, out IDictionary <string, string> serverSettings, out AnalyzerSettings analyzerSettings)
        {
            string hostUrl = args.GetSetting(SonarProperties.HostUrl);

            serverSettings   = null;
            analyzerSettings = null;

            ISonarQubeServer server = this.factory.CreateSonarQubeServer(args, this.logger);

            try
            {
                this.logger.LogInfo(Resources.MSG_FetchingAnalysisConfiguration);

                // Respect sonar.branch setting if set
                string projectBranch = null;
                args.TryGetSetting(SonarProperties.ProjectBranch, out projectBranch);

                // Fetch the SonarQube project properties
                serverSettings = server.GetProperties(args.ProjectKey, projectBranch);

                // Generate the FxCop rulesets
                this.logger.LogInfo(Resources.MSG_GeneratingRulesets);
                GenerateFxCopRuleset(server, args.ProjectKey, projectBranch,
                                     "csharp", "cs", "fxcop", Path.Combine(settings.SonarConfigDirectory, FxCopCSharpRuleset));
                GenerateFxCopRuleset(server, args.ProjectKey, projectBranch,
                                     "vbnet", "vbnet", "fxcop-vbnet", Path.Combine(settings.SonarConfigDirectory, FxCopVBNetRuleset));

                IAnalyzerProvider analyzerProvider = this.factory.CreateAnalyzerProvider(this.logger);
                Debug.Assert(analyzerProvider != null, "Factory should not return null");

                analyzerSettings = analyzerProvider.SetupAnalyzers(server, settings, args.ProjectKey, projectBranch);
            }
            catch (WebException ex)
            {
                if (Utilities.HandleHostUrlWebException(ex, hostUrl, this.logger))
                {
                    return(false);
                }

                throw;
            }
            finally
            {
                Utilities.SafeDispose(server);
            }

            return(true);
        }
Example #17
0
        private static void FetchBinaries(ISonarQubeServer server, TeamBuildSettings settings, ILogger logger)
        {
            // For the 1.1 release of the runner/scanner, we are hard-coding support for a single known version
            // of SonarLint. The required assemblies will be packaged in the "static" folder of the jar (in the
            // same way that the SonarQube.MSBuild.Runner.Implementation.zip file is).
            logger.LogDebug(Resources.SLAP_FetchingSonarLintAnalyzer);
            if (server.TryDownloadEmbeddedFile(CSharpPluginKey, EmbeddedSonarLintZipFileName, settings.SonarBinDirectory))
            {
                string filePath = Path.Combine(settings.SonarBinDirectory, EmbeddedSonarLintZipFileName);

                logger.LogDebug(Resources.MSG_ExtractingFiles, settings.SonarBinDirectory);
                ZipFile.ExtractToDirectory(filePath, settings.SonarBinDirectory);
            }
            else
            {
                logger.LogDebug(Resources.SLAP_AnalyzerNotFound);
            }
        }
        public ISonarQubeServer CreateSonarQubeServer(ProcessedArgs args, ILogger logger)
        {
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            string username = args.GetSetting(SonarProperties.SonarUserName, null);
            string password = args.GetSetting(SonarProperties.SonarPassword, null);
            string hostUrl = args.GetSetting(SonarProperties.HostUrl, null);

            this.server = new SonarWebService(new WebClientDownloader(username, password, logger), hostUrl, logger);
            return server;
        }
        public ISonarQubeServer CreateSonarQubeServer(ProcessedArgs args, ILogger logger)
        {
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            string username = args.GetSetting(SonarProperties.SonarUserName, null);
            string password = args.GetSetting(SonarProperties.SonarPassword, null);
            string hostUrl  = args.SonarQubeUrl;

            this.server = new SonarWebService(new WebClientDownloader(username, password, logger), hostUrl, logger);
            return(server);
        }
        private static void FetchBinaries(ISonarQubeServer server, TeamBuildSettings settings, ILogger logger)
        {
            // For the 1.1 release of the runner/scanner, we are hard-coding support for a single known version
            // of SonarLint. The required assemblies will be packaged in the "static" folder of the jar (in the
            // same way that the SonarQube.MSBuild.Runner.Implementation.zip file is).
            logger.LogDebug(Resources.SLAP_FetchingSonarLintAnalyzer);
            if (server.TryDownloadEmbeddedFile(CSharpPluginKey, EmbeddedSonarLintZipFileName, settings.SonarBinDirectory))
            {
                string filePath = Path.Combine(settings.SonarBinDirectory, EmbeddedSonarLintZipFileName);

                logger.LogDebug(Resources.MSG_ExtractingFiles, settings.SonarBinDirectory);
                ZipFile.ExtractToDirectory(filePath, settings.SonarBinDirectory);
            }
            else
            {
                logger.LogDebug(Resources.SLAP_AnalyzerNotFound);
            }
        }
        public EmbeddedAnalyzerInstaller(ISonarQubeServer server, string localCacheDirectory, ILogger logger)
        {
            if (server == null)
            {
                throw new ArgumentNullException("server");
            }
            if (string.IsNullOrWhiteSpace(localCacheDirectory))
            {
                throw new ArgumentNullException("localCacheDirectory");
            }
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            this.server = server;
            this.localCacheDirectory = localCacheDirectory;
            this.logger = logger;
        }
        public EmbeddedAnalyzerInstaller(ISonarQubeServer server, string localCacheDirectory, ILogger logger)
        {
            if (server == null)
            {
                throw new ArgumentNullException("server");
            }
            if (string.IsNullOrWhiteSpace(localCacheDirectory))
            {
                throw new ArgumentNullException("localCacheDirectory");
            }
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            this.server = server;
            this.localCacheDirectory = localCacheDirectory;
            this.logger = logger;
        }
        private bool DoExecute(ProcessedArgs localSettings)
        {
            Debug.Assert(localSettings != null, "Not expecting the process arguments to be null");

            this.logger.Verbosity = VerbosityCalculator.ComputeVerbosity(localSettings.AggregateProperties, this.logger);
            logger.ResumeOutput();

            InstallLoaderTargets(localSettings);

            TeamBuildSettings teamBuildSettings = TeamBuildSettings.GetSettingsFromEnvironment(this.logger);

            // We're checking the args and environment variables so we can report all config errors to the user at once
            if (teamBuildSettings == null)
            {
                this.logger.LogError(Resources.ERROR_CannotPerformProcessing);
                return(false);
            }

            // Create the directories
            this.logger.LogDebug(Resources.MSG_CreatingFolders);
            if (!Utilities.TryEnsureEmptyDirectories(this.logger,
                                                     teamBuildSettings.SonarConfigDirectory,
                                                     teamBuildSettings.SonarOutputDirectory))
            {
                return(false);
            }

            ISonarQubeServer server = this.factory.CreateSonarQubeServer(localSettings, this.logger);

            IDictionary <string, string> serverSettings;
            List <AnalyzerSettings>      analyzersSettings;

            if (!FetchArgumentsAndRulesets(server, localSettings, teamBuildSettings, out serverSettings, out analyzersSettings))
            {
                return(false);
            }
            Debug.Assert(analyzersSettings != null, "Not expecting the analyzers settings to be null");

            // analyzerSettings can be empty
            AnalysisConfigGenerator.GenerateFile(localSettings, teamBuildSettings, serverSettings, analyzersSettings, this.logger);

            return(true);
        }
Example #24
0
        private static bool TryCreateRuleset(ISonarQubeServer server, TeamBuildSettings settings, string projectKey, ILogger logger)
        {
            logger.LogDebug(Resources.SLAP_FetchingSonarLintRuleset);
            string content = TryGetProfileExportForProject(server, projectKey, logger);

            if (content != null)
            {
                if (IsValidRuleset(content))
                {
                    string ruleSetFilePath = GetRulesetFilePath(settings);
                    logger.LogDebug(Resources.SLAP_SonarLintRulesetCreated, ruleSetFilePath);

                    File.WriteAllText(ruleSetFilePath, content);
                    return(true);
                }
                else
                {
                    logger.LogError(Resources.SLAP_InvalidRulesetReturned);
                }
            }
            return(false);
        }
Example #25
0
        private static string TryGetProfileExportForProject(ISonarQubeServer server, string projectKey, ILogger logger)
        {
            string profileContent = null;

            string qualityProfile;

            if (server.TryGetQualityProfile(projectKey, CSharpLanguage, out qualityProfile))
            {
                if (server.TryGetProfileExport(qualityProfile, CSharpLanguage, SonarLintProfileFormatName, out profileContent))
                {
                    logger.LogDebug(Resources.SLAP_ProfileExportFound, projectKey);
                }
                else
                {
                    logger.LogDebug(Resources.SLAP_ProfileExportNotFound, projectKey);
                }
            }
            else
            {
                logger.LogDebug(Resources.SLAP_NoProfileForProject, projectKey);
            }
            return(profileContent);
        }
Example #26
0
        public AnalyzerSettings SetupAnalyzers(ISonarQubeServer server, TeamBuildSettings settings, string projectKey, string projectBranch)
        {
            if (server == null)
            {
                throw new ArgumentNullException("server");
            }
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }
            if (string.IsNullOrWhiteSpace(projectKey))
            {
                throw new ArgumentNullException("projectKey");
            }

            AnalyzerSettings analyzerSettings = null;

            if (IsCSharpPluginInstalled(server))
            {
                this.sqServer        = server;
                this.sqSettings      = settings;
                this.sqProjectKey    = projectKey;
                this.sqProjectBranch = projectBranch;

                RoslynExportProfile profile = TryGetRoslynConfigForProject();
                if (profile != null)
                {
                    analyzerSettings = ProcessProfile(profile);
                }
            }
            else
            {
                logger.LogDebug(Resources.RAP_CSharpPluginNotInstalled);
            }

            return(analyzerSettings ?? new AnalyzerSettings()); // return emtpy settings rather than null
        }
Example #27
0
        private bool FetchArgumentsAndRulesets(ProcessedArgs args, TeamBuildSettings settings, ILogger logger, out IDictionary <string, string> serverSettings)
        {
            string hostUrl = args.GetSetting(SonarProperties.HostUrl);

            serverSettings = null;

            ISonarQubeServer server = this.serverFactory.Create(args, logger);

            try
            {
                // Fetch the SonarQube project properties
                logger.LogInfo(Resources.MSG_FetchingAnalysisConfiguration);
                serverSettings = server.GetProperties(args.ProjectKey);

                // Generate the FxCop rulesets
                logger.LogInfo(Resources.MSG_GeneratingRulesets);
                GenerateFxCopRuleset(server, args.ProjectKey, "csharp", "cs", "fxcop", Path.Combine(settings.SonarConfigDirectory, FxCopCSharpRuleset), logger);
                GenerateFxCopRuleset(server, args.ProjectKey, "vbnet", "vbnet", "fxcop-vbnet", Path.Combine(settings.SonarConfigDirectory, FxCopVBNetRuleset), logger);

                SonarLintAnalyzerProvider.SetupAnalyzers(server, settings, args.ProjectKey, logger);
            }
            catch (WebException ex)
            {
                if (Utilities.HandleHostUrlWebException(ex, hostUrl, logger))
                {
                    return(false);
                }

                throw;
            }
            finally
            {
                Utilities.SafeDispose(server);
            }

            return(true);
        }
 public EmbeddedAnalyzerInstaller(ISonarQubeServer server, ILogger logger)
     : this(server, GetLocalCacheDirectory(), logger)
 {
 }
Example #29
0
 public EmbeddedAnalyzerInstaller(ISonarQubeServer server, ILogger logger)
     : this(server, GetLocalCacheDirectory(), logger)
 {
 }
        private static bool TryCreateRuleset(ISonarQubeServer server, TeamBuildSettings settings, string projectKey, ILogger logger)
        {
            logger.LogDebug(Resources.SLAP_FetchingSonarLintRuleset);
            string content = TryGetProfileExportForProject(server, projectKey, logger);

            if (content != null)
            {
                if (IsValidRuleset(content))
                {
                    string ruleSetFilePath = GetRulesetFilePath(settings);
                    logger.LogDebug(Resources.SLAP_SonarLintRulesetCreated, ruleSetFilePath);

                    File.WriteAllText(ruleSetFilePath, content);
                    return true;
                }
                else
                {
                    // TODO: decide on an appropriate error message once we know whether could
                    // happen in the 1.1 release.
                    logger.LogError(Resources.SLAP_InvalidRulesetReturned);
                }
            }
            return false;
        }
 public MockObjectFactory(ISonarQubeServer server)
 {
     this.server = server;
 }
 private static void FetchBinaries(ISonarQubeServer server, TeamBuildSettings settings, ILogger logger)
 {
     // TODO: https://jira.sonarsource.com/browse/SONARCS-556
 }
        private static bool TryGetProfileExportForProject(ISonarQubeServer server, string projectKey, ILogger logger, out string rulesetContent, out string parametersContent)
        {
            string qualityProfile;
            if (!server.TryGetQualityProfile(projectKey, CSharpLanguage, out qualityProfile))
            {
                logger.LogDebug(Resources.SLAP_NoProfileForProject, projectKey);
                rulesetContent = null;
                parametersContent = null;
                return false;
            }

            if (!server.TryGetProfileExport(qualityProfile, CSharpLanguage, SonarLintProfileFormatName, out rulesetContent))
            {
                logger.LogDebug(Resources.SLAP_ProfileExportNotFound, SonarLintProfileFormatName, projectKey);
                parametersContent = null;
                return false;
            }
            logger.LogDebug(Resources.SLAP_ProfileExportFound, SonarLintProfileFormatName, projectKey);

            if (!server.TryGetProfileExport(qualityProfile, CSharpLanguage, SonarLintParametersFormatName, out parametersContent))
            {
                logger.LogDebug(Resources.SLAP_ProfileExportNotFound, SonarLintParametersFormatName, projectKey);
                return false;
            }
            logger.LogDebug(Resources.SLAP_ProfileExportFound, SonarLintParametersFormatName, projectKey);

            return true;
        }
Example #34
0
        private bool FetchArgumentsAndRulesets(ISonarQubeServer server, ProcessedArgs args, TeamBuildSettings settings, out IDictionary <string, string> serverSettings, out List <AnalyzerSettings> analyzersSettings)
        {
            serverSettings    = null;
            analyzersSettings = new List <AnalyzerSettings>();

            try
            {
                logger.LogInfo(Resources.MSG_FetchingAnalysisConfiguration);

                // Respect sonar.branch setting if set
                args.TryGetSetting(SonarProperties.ProjectBranch, out string projectBranch);

                // Fetch the SonarQube project properties
                serverSettings = server.GetProperties(args.ProjectKey, projectBranch);

                // Fetch installed plugins
                var availableLanguages = server.GetAllLanguages();

                foreach (var plugin in plugins)
                {
                    if (!availableLanguages.Contains(plugin.Language))
                    {
                        continue;
                    }

                    // Fetch project quality profile
                    if (!server.TryGetQualityProfile(args.ProjectKey, projectBranch, args.Organization, plugin.Language, out string qualityProfile))
                    {
                        logger.LogDebug(Resources.RAP_NoQualityProfile, plugin.Language, args.ProjectKey);
                        continue;
                    }

                    // Fetch rules (active and not active)
                    var activeRules = server.GetActiveRules(qualityProfile);

                    if (!activeRules.Any())
                    {
                        logger.LogDebug(Resources.RAP_NoActiveRules, plugin.Language);
                        continue;
                    }

                    var inactiveRules = server.GetInactiveRules(qualityProfile, plugin.Language);

                    // Generate Roslyn analyzers settings and rulesets
                    var analyzerProvider = factory.CreateRoslynAnalyzerProvider();
                    Debug.Assert(analyzerProvider != null, "Factory should not return null");

                    // Will be null if the processing of server settings and active rules resulted in an empty ruleset
                    var analyzer = analyzerProvider.SetupAnalyzer(settings, serverSettings, activeRules, inactiveRules, plugin.Language);

                    if (analyzer != null)
                    {
                        analyzersSettings.Add(analyzer);
                    }
                }
            }
            catch (WebException ex)
            {
                if (Utilities.HandleHostUrlWebException(ex, args.SonarQubeUrl, logger))
                {
                    return(false);
                }

                throw;
            }
            finally
            {
                Utilities.SafeDispose(server);
            }

            return(true);
        }
Example #35
0
        /// <summary>
        /// Combines the various configuration options into the AnalysisConfig file
        /// used by the build and post-processor. Saves the file and returns the config instance.
        /// </summary>
        /// <param name="localSettings">Processed local settings, including command line arguments supplied the user</param>
        /// <param name="buildSettings">Build environment settings</param>
        /// <param name="serverProperties">Analysis properties downloaded from the SonarQube server</param>
        /// <param name="analyzerSettings">Specifies the Roslyn analyzers to use. Can be empty</param>
        public static AnalysisConfig GenerateFile(ProcessedArgs localSettings,
                                                  TeamBuildSettings buildSettings,
                                                  IDictionary <string, string> serverProperties,
                                                  List <AnalyzerSettings> analyzersSettings,
                                                  ISonarQubeServer sonarQubeServer,
                                                  ILogger logger)
        {
            if (localSettings == null)
            {
                throw new ArgumentNullException(nameof(localSettings));
            }
            if (buildSettings == null)
            {
                throw new ArgumentNullException(nameof(buildSettings));
            }
            if (serverProperties == null)
            {
                throw new ArgumentNullException(nameof(serverProperties));
            }
            if (sonarQubeServer == null)
            {
                throw new ArgumentNullException(nameof(sonarQubeServer));
            }
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            var config = new AnalysisConfig
            {
                SonarProjectKey     = localSettings.ProjectKey,
                SonarProjectName    = localSettings.ProjectName,
                SonarProjectVersion = localSettings.ProjectVersion,
                SonarQubeHostUrl    = localSettings.SonarQubeUrl,
                HasBeginStepCommandLineCredentials = localSettings.CmdLineProperties.HasProperty(SonarProperties.SonarUserName),
                SonarQubeVersion = sonarQubeServer.GetServerVersion().Result.ToString()
            };

            config.SetBuildUri(buildSettings.BuildUri);
            config.SetTfsUri(buildSettings.TfsUri);
            config.SetVsCoverageConverterToolPath(buildSettings.CoverageToolUserSuppliedPath);

            config.SonarConfigDir = buildSettings.SonarConfigDirectory;
            config.SonarOutputDir = buildSettings.SonarOutputDirectory;
            config.SonarBinDir    = buildSettings.SonarBinDirectory;
            config.SonarScannerWorkingDirectory = buildSettings.SonarScannerWorkingDirectory;
            config.SourcesDirectory             = buildSettings.SourcesDirectory;

            // Add the server properties to the config
            config.ServerSettings = new AnalysisProperties();

            foreach (var property in serverProperties)
            {
                if (!Utilities.IsSecuredServerProperty(property.Key))
                {
                    AddSetting(config.ServerSettings, property.Key, property.Value);
                }
            }

            config.LocalSettings = new AnalysisProperties();
            // From the local settings, we only write the ones coming from the cmd line
            foreach (var property in localSettings.CmdLineProperties.GetAllProperties())
            {
                AddSetting(config.LocalSettings, property.Id, property.Value);
            }

            if (!string.IsNullOrEmpty(localSettings.Organization))
            {
                AddSetting(config.LocalSettings, SonarProperties.Organization, localSettings.Organization);
            }

            // Set the pointer to the properties file
            if (localSettings.PropertiesFileName != null)
            {
                config.SetSettingsFilePath(localSettings.PropertiesFileName);
            }

            config.AnalyzersSettings = analyzersSettings ?? throw new ArgumentNullException(nameof(analyzersSettings));
            config.Save(buildSettings.AnalysisConfigFilePath);

            return(config);
        }
 private AnalysisProperties InstallBuildWrapper(ISonarQubeServer server, string binDirectory, string outputDirectory)
 {
     IBuildWrapperInstaller installer = this.factory.CreateBuildWrapperInstaller(this.logger);
     Debug.Assert(installer != null, "Factory should not return null");
     return installer.InstallBuildWrapper(server, binDirectory, outputDirectory);
 }
        private async Task <ArgumentsAndRuleSets> FetchArgumentsAndRulesets(ISonarQubeServer server, ProcessedArgs args, TeamBuildSettings settings)
        {
            ArgumentsAndRuleSets argumentsAndRuleSets = new ArgumentsAndRuleSets();

            try
            {
                this.logger.LogInfo(Resources.MSG_FetchingAnalysisConfiguration);

                // Respect sonar.branch setting if set
                args.TryGetSetting(SonarProperties.ProjectBranch, out var projectBranch);

                // Fetch the SonarQube project properties
                argumentsAndRuleSets.ServerSettings = await server.GetProperties(args.ProjectKey, projectBranch);

                // Fetch installed plugins
                var availableLanguages = await server.GetAllLanguages();

                foreach (var plugin in plugins)
                {
                    if (!availableLanguages.Contains(plugin.Language))
                    {
                        continue;
                    }

                    var qualityProfile = await server.TryGetQualityProfile(args.ProjectKey, projectBranch, args.Organization, plugin.Language);

                    // Fetch project quality profile
                    if (!qualityProfile.Item1)
                    {
                        this.logger.LogDebug(Resources.RAP_NoQualityProfile, plugin.Language, args.ProjectKey);
                        continue;
                    }

                    // Fetch rules (active and not active)
                    var activeRules = await server.GetActiveRules(qualityProfile.Item2);

                    if (!activeRules.Any())
                    {
                        this.logger.LogDebug(Resources.RAP_NoActiveRules, plugin.Language);
                    }

                    var inactiveRules = await server.GetInactiveRules(qualityProfile.Item2, plugin.Language);

                    // Generate Roslyn analyzers settings and rulesets
                    var analyzerProvider = this.factory.CreateRoslynAnalyzerProvider();
                    Debug.Assert(analyzerProvider != null, "Factory should not return null");

                    // Will be null if the processing of server settings and active rules resulted in an empty ruleset

                    // Use the aggregate of local and server properties when generating the analyzer configuration
                    // See bug 699: https://github.com/SonarSource/sonar-scanner-msbuild/issues/699
                    var serverProperties = new ListPropertiesProvider(argumentsAndRuleSets.ServerSettings);
                    var allProperties    = new AggregatePropertiesProvider(args.AggregateProperties, serverProperties);
                    var analyzer         = analyzerProvider.SetupAnalyzer(settings, allProperties, activeRules, inactiveRules, plugin.Language);

                    if (analyzer != null)
                    {
                        argumentsAndRuleSets.AnalyzersSettings.Add(analyzer);
                    }
                }
            }
            catch (WebException ex)
            {
                if (Utilities.HandleHostUrlWebException(ex, args.SonarQubeUrl, this.logger))
                {
                    argumentsAndRuleSets.IsSuccess = false;
                    return(argumentsAndRuleSets);
                }

                throw;
            }
            finally
            {
                Utilities.SafeDispose(server);
            }

            argumentsAndRuleSets.IsSuccess = true;
            return(argumentsAndRuleSets);
        }
Example #38
0
 private static void GenerateFxCopRuleset(ISonarQubeServer server, string projectKey, string requiredPluginKey, string language, string repository, string path, ILogger logger)
 {
     logger.LogDebug(Resources.MSG_GeneratingRuleset, path);
     RulesetGenerator.Generate(server, requiredPluginKey, language, repository, projectKey, path);
 }
 public MockObjectFactory(ISonarQubeServer server)
 {
     this.server = server;
 }
Example #40
0
 private static bool IsCSharpPluginInstalled(ISonarQubeServer server)
 {
     return(server.GetInstalledPlugins().Contains(CSharpPluginKey));
 }
        private static string TryGetProfileExportForProject(ISonarQubeServer server, string projectKey, ILogger logger)
        {
            string profileContent = null;

            string qualityProfile;
            if (server.TryGetQualityProfile(projectKey, CSharpLanguage, out qualityProfile))
            {
                if (server.TryGetProfileExport(qualityProfile, CSharpLanguage, SonarLintProfileFormatName, out profileContent))
                {
                    logger.LogDebug(Resources.SLAP_ProfileExportFound, projectKey);
                }
                else
                {
                    logger.LogDebug(Resources.SLAP_ProfileExportNotFound, projectKey);
                }
            }
            else
            {
                logger.LogDebug(Resources.SLAP_NoProfileForProject, projectKey);
            }
            return profileContent;
        }
        private bool FetchArgumentsAndRulesets(ISonarQubeServer server, ProcessedArgs args, TeamBuildSettings settings, out IDictionary<string, string> serverSettings, out AnalyzerSettings analyzerSettings)
        {
            string hostUrl = args.GetSetting(SonarProperties.HostUrl);
            serverSettings = null;
            analyzerSettings = null;

            try
            {
                this.logger.LogInfo(Resources.MSG_FetchingAnalysisConfiguration);

                // Respect sonar.branch setting if set
                string projectBranch = null;
                args.TryGetSetting(SonarProperties.ProjectBranch, out projectBranch);

                // Fetch the SonarQube project properties
                serverSettings = server.GetProperties(args.ProjectKey, projectBranch);

                // Generate the FxCop rulesets
                this.logger.LogInfo(Resources.MSG_GeneratingRulesets);
                GenerateFxCopRuleset(server, args.ProjectKey, projectBranch,
                    "csharp", "cs", "fxcop", Path.Combine(settings.SonarConfigDirectory, FxCopCSharpRuleset));
                GenerateFxCopRuleset(server, args.ProjectKey, projectBranch,
                    "vbnet", "vbnet", "fxcop-vbnet", Path.Combine(settings.SonarConfigDirectory, FxCopVBNetRuleset));

                IAnalyzerProvider analyzerProvider = this.factory.CreateAnalyzerProvider(this.logger);
                Debug.Assert(analyzerProvider != null, "Factory should not return null");

                analyzerSettings = analyzerProvider.SetupAnalyzers(server, settings, args.ProjectKey, projectBranch);
            }
            catch (WebException ex)
            {
                if (Utilities.HandleHostUrlWebException(ex, hostUrl, this.logger))
                {
                    return false;
                }

                throw;
            }
            finally
            {
                Utilities.SafeDispose(server);
            }

            return true;
        }
 public MockSonarQubeServerFactory(ISonarQubeServer server)
 {
     this.server = server;
 }
 private static bool IsCppPluginInstalled(ISonarQubeServer server)
 {
     return server.GetInstalledPlugins().Contains(CppPluginKey);
 }
 public MockSonarQubeServerFactory(ISonarQubeServer server)
 {
     this.server = server;
 }
 private void GenerateFxCopRuleset(ISonarQubeServer server, string projectKey, string projectBranch, string requiredPluginKey, string language, string repository, string path)
 {
     this.logger.LogDebug(Resources.MSG_GeneratingRuleset, path);
     RulesetGenerator.Generate(server, requiredPluginKey, language, repository, projectKey, projectBranch, path);
 }
        private bool FetchArgumentsAndRulesets(ISonarQubeServer server, ProcessedArgs args, TeamBuildSettings settings, out IDictionary <string, string> serverSettings, out List <AnalyzerSettings> analyzersSettings)
        {
            serverSettings    = null;
            analyzersSettings = new List <AnalyzerSettings>();

            try
            {
                this.logger.LogInfo(Resources.MSG_FetchingAnalysisConfiguration);

                // Respect sonar.branch setting if set
                string projectBranch = null;
                args.TryGetSetting(SonarProperties.ProjectBranch, out projectBranch);

                // Fetch the SonarQube project properties
                serverSettings = server.GetProperties(args.ProjectKey, projectBranch);

                // Fetch installed plugins
                IEnumerable <string> availableLanguages = server.GetAllLanguages();

                foreach (PluginDefinition plugin in plugins)
                {
                    if (!availableLanguages.Contains(plugin.Language))
                    {
                        continue;
                    }

                    // Fetch project quality profile
                    string qualityProfile;
                    if (!server.TryGetQualityProfile(args.ProjectKey, projectBranch, args.Organization, plugin.Language, out qualityProfile))
                    {
                        this.logger.LogDebug(Resources.RAP_NoQualityProfile, plugin.Language, args.ProjectKey);
                        continue;
                    }

                    // Fetch rules (active and not active)
                    IList <ActiveRule> activeRules = server.GetActiveRules(qualityProfile);

                    if (!activeRules.Any())
                    {
                        this.logger.LogDebug(Resources.RAP_NoActiveRules, plugin.Language);
                        continue;
                    }

                    IList <string> inactiveRules = server.GetInactiveRules(qualityProfile, plugin.Language);

                    // Generate fxcop rulesets
                    this.logger.LogInfo(Resources.MSG_GeneratingRulesets);
                    string fxCopPath = Path.Combine(settings.SonarConfigDirectory, string.Format(FxCopRulesetName, plugin.Language));
                    if (plugin.Language.Equals(VBNetLanguage))
                    {
                        GenerateFxCopRuleset("fxcop-vbnet", activeRules, fxCopPath);
                    }
                    else
                    {
                        GenerateFxCopRuleset("fxcop", activeRules, fxCopPath);
                    }

                    // Generate Roslyn analyzers settings and rulesets
                    IAnalyzerProvider analyzerProvider = this.factory.CreateRoslynAnalyzerProvider(this.logger);
                    Debug.Assert(analyzerProvider != null, "Factory should not return null");

                    // Will be null if the processing of server settings and active rules resulted in an empty ruleset
                    AnalyzerSettings analyzer = analyzerProvider.SetupAnalyzer(settings, serverSettings, activeRules, inactiveRules, plugin.Language);

                    if (analyzer != null)
                    {
                        analyzersSettings.Add(analyzer);
                    }
                }
            }
            catch (WebException ex)
            {
                if (Utilities.HandleHostUrlWebException(ex, args.SonarQubeUrl, this.logger))
                {
                    return(false);
                }

                throw;
            }
            finally
            {
                Utilities.SafeDispose(server);
            }

            return(true);
        }