public ProcessedArgs(string key, string name, string version, bool installLoaderTargets, IAnalysisPropertyProvider cmdLineProperties, IAnalysisPropertyProvider globalFileProperties)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                throw new ArgumentNullException("key");
            }
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentNullException("name");
            }
            if (string.IsNullOrWhiteSpace(version))
            {
                throw new ArgumentNullException("version");
            }
            if (cmdLineProperties == null)
            {
                throw new ArgumentNullException("cmdLineProperties");
            }
            if (globalFileProperties == null)
            {
                throw new ArgumentNullException("globalFileProperties");
            }

            this.projectKey = key;
            this.projectName = name;
            this.projectVersion = version;

            this.cmdLineProperties = cmdLineProperties;
            this.globalFileProperties = globalFileProperties;
            this.InstallLoaderTargets = installLoaderTargets;

            this.aggProperties = new AggregatePropertiesProvider(cmdLineProperties, globalFileProperties);
        }
Example #2
0
        public static void AssertExpectedPropertyCount(this IAnalysisPropertyProvider provider, int expected)
        {
            var allProperties = provider.GetAllProperties();

            allProperties.Should().NotBeNull("Returned list of properties should not be null");
            allProperties.Should().HaveCount(expected, "Unexpected number of properties returned");
        }
        public ProcessedArgs(string key, string name, string version, string organization, bool installLoaderTargets,
                             IAnalysisPropertyProvider cmdLineProperties, IAnalysisPropertyProvider globalFileProperties,
                             IAnalysisPropertyProvider scannerEnvProperties, ILogger logger)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                throw new ArgumentNullException(nameof(key));
            }

            ProjectKey     = key;
            ProjectName    = name;
            ProjectVersion = version;
            Organization   = organization;

            CmdLineProperties         = cmdLineProperties ?? throw new ArgumentNullException(nameof(cmdLineProperties));
            this.globalFileProperties = globalFileProperties ?? throw new ArgumentNullException(nameof(globalFileProperties));
            ScannerEnvProperties      = scannerEnvProperties ?? throw new ArgumentNullException(nameof(scannerEnvProperties));
            InstallLoaderTargets      = installLoaderTargets;

            if (Organization == null && this.globalFileProperties.TryGetValue(SonarProperties.Organization, out var filePropertiesOrganization))
            {
                logger.LogError(Resources.ERROR_Organization_Provided_In_SonarQubeAnalysis_file);
                IsOrganizationValid = false;
            }
            else
            {
                IsOrganizationValid = true;
            }

            AggregateProperties = new AggregatePropertiesProvider(cmdLineProperties, globalFileProperties, ScannerEnvProperties);
            if (!AggregateProperties.TryGetValue(SonarProperties.HostUrl, out this.sonarQubeUrl))
            {
                this.sonarQubeUrl = "http://localhost:9000";
            }
        }
        private static FilePropertyProvider AssertIsFilePropertyProvider(IAnalysisPropertyProvider actualProvider)
        {
            Assert.IsNotNull(actualProvider, "Supplied provider should not be null");
            Assert.IsInstanceOfType(actualProvider, typeof(FilePropertyProvider), "Expecting a file provider");

            return((FilePropertyProvider)actualProvider);
        }
        private static void AssertExpectedPropertiesFile(string expectedFilePath, IAnalysisPropertyProvider actualProvider)
        {
            FilePropertyProvider fileProvider = AssertIsFilePropertyProvider(actualProvider);

            Assert.IsNotNull(fileProvider.PropertiesFile, "Properties file object should not be null");
            Assert.AreEqual(expectedFilePath, fileProvider.PropertiesFile.FilePath, "Properties were not loaded from the expected location");
        }
Example #6
0
        public static void AssertExpectedPropertyCount(this IAnalysisPropertyProvider provider, int expected)
        {
            var allProperties = provider.GetAllProperties();

            Assert.IsNotNull(allProperties, "Returned list of properties should not be null");
            Assert.AreEqual(expected, allProperties.Count(), "Unexpected number of properties returned");
        }
Example #7
0
        public static void AssertExpectedPropertyValue(this IAnalysisPropertyProvider provider, string key, string expectedValue)
        {
            var found = provider.TryGetProperty(key, out Property property);

            Assert.IsTrue(found, "Expected property was not found. Key: {0}", key);
            Assert.AreEqual(expectedValue, property.Value, "");
        }
        public void FileProvider_UseSpecifiedPropertiesFile()
        {
            // Arrange
            string testDir             = TestUtils.CreateTestSpecificFolder(this.TestContext);
            string validPropertiesFile = CreateValidPropertiesFile(testDir, "myPropertiesFile.xml", "xxx", "value with spaces");

            string defaultPropertiesDir = TestUtils.CreateTestSpecificFolder(this.TestContext, "Default");

            CreateFile(defaultPropertiesDir, FilePropertyProvider.DefaultFileName, "invalid file - will error if this file is loaded");

            IList <ArgumentInstance> args = new List <ArgumentInstance>
            {
                new ArgumentInstance(FilePropertyProvider.Descriptor, validPropertiesFile)
            };

            TestLogger logger = new TestLogger();

            // Act
            IAnalysisPropertyProvider provider = CheckProcessingSucceeds(args, defaultPropertiesDir, logger);

            // Assert
            AssertExpectedPropertiesFile(validPropertiesFile, provider);
            provider.AssertExpectedPropertyValue("xxx", "value with spaces");
            AssertIsNotDefaultPropertiesFile(provider);
        }
        /// <summary>
        /// Attempts to construct and return a provider that uses analysis properties provided on the command line
        /// </summary>
        /// <param name="commandLineArguments">List of command line arguments (optional)</param>
        /// <returns>False if errors occurred when constructing the provider, otherwise true</returns>
        /// <remarks>If no properties were provided on the command line then an empty provider will be returned</remarks>
        public static bool TryCreateProvider(IEnumerable<ArgumentInstance> commandLineArguments, ILogger logger, out IAnalysisPropertyProvider provider)
        {
            if (commandLineArguments == null)
            {
                throw new ArgumentNullException("commandLineArguments");
            }
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            IEnumerable<Property> validProperties;
            if (ExtractAndValidateProperties(commandLineArguments, logger, out validProperties))
            {
                if (validProperties.Any())
                {
                    provider = new CmdLineArgPropertyProvider(validProperties);
                }
                else
                {
                    provider = EmptyPropertyProvider.Instance;
                }

                return true;
            }

            provider = null;
            return false;
        }
Example #10
0
        public void ConfigExt_GetAnalysisSettings_LocalOnly()
        {
            // Check that local settings are always retrieved by GetAnalysisSettings

            // 0. Setup
            AnalysisConfig config = new AnalysisConfig
            {
                LocalSettings = new AnalysisProperties()
            };

            config.LocalSettings.Add(new Property()
            {
                Id = "local.1", Value = "local.value.1"
            });
            config.LocalSettings.Add(new Property()
            {
                Id = "local.2", Value = "local.value.2"
            });

            // 1. Local only
            IAnalysisPropertyProvider localProperties = config.GetAnalysisSettings(false);

            localProperties.AssertExpectedPropertyCount(2);
            localProperties.AssertExpectedPropertyValue("local.1", "local.value.1");
            localProperties.AssertExpectedPropertyValue("local.2", "local.value.2");

            // 2. Local and server
            IAnalysisPropertyProvider allProperties = config.GetAnalysisSettings(true);

            allProperties.AssertExpectedPropertyCount(2);
            allProperties.AssertExpectedPropertyValue("local.1", "local.value.1");
            allProperties.AssertExpectedPropertyValue("local.2", "local.value.2");
        }
Example #11
0
        public ProcessedArgs(string key, string name, string version, bool installLoaderTargets, IAnalysisPropertyProvider cmdLineProperties,
                             IAnalysisPropertyProvider globalFileProperties, IAnalysisPropertyProvider scannerEnvProperties)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                throw new ArgumentNullException("key");
            }
            if (cmdLineProperties == null)
            {
                throw new ArgumentNullException("cmdLineProperties");
            }
            if (globalFileProperties == null)
            {
                throw new ArgumentNullException("globalFileProperties");
            }
            if (scannerEnvProperties == null)
            {
                throw new ArgumentNullException("scannerEnvProperties");
            }

            this.projectKey     = key;
            this.projectName    = name;
            this.projectVersion = version;

            this.cmdLineProperties    = cmdLineProperties;
            this.globalFileProperties = globalFileProperties;
            this.scannerEnvProperties = scannerEnvProperties;
            this.InstallLoaderTargets = installLoaderTargets;

            this.aggProperties = new AggregatePropertiesProvider(cmdLineProperties, globalFileProperties, scannerEnvProperties);
            if (!aggProperties.TryGetValue(SonarProperties.HostUrl, out this.sonarQubeUrl))
            {
                this.sonarQubeUrl = "http://localhost:9000";
            }
        }
Example #12
0
        public ProcessedArgs(string key, string name, string version, bool installLoaderTargets, IAnalysisPropertyProvider cmdLineProperties, IAnalysisPropertyProvider globalFileProperties)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                throw new ArgumentNullException("key");
            }
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentNullException("name");
            }
            if (string.IsNullOrWhiteSpace(version))
            {
                throw new ArgumentNullException("version");
            }
            if (cmdLineProperties == null)
            {
                throw new ArgumentNullException("cmdLineProperties");
            }
            if (globalFileProperties == null)
            {
                throw new ArgumentNullException("globalFileProperties");
            }

            this.projectKey     = key;
            this.projectName    = name;
            this.projectVersion = version;

            this.cmdLineProperties    = cmdLineProperties;
            this.globalFileProperties = globalFileProperties;
            this.InstallLoaderTargets = installLoaderTargets;

            this.aggProperties = new AggregatePropertiesProvider(cmdLineProperties, globalFileProperties);
        }
Example #13
0
        public ProcessedArgs(string key, string name, string version, string organization, bool installLoaderTargets,
                             IAnalysisPropertyProvider cmdLineProperties, IAnalysisPropertyProvider globalFileProperties,
                             IAnalysisPropertyProvider scannerEnvProperties)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                throw new ArgumentNullException("key");
            }

            ProjectKey     = key;
            ProjectName    = name;
            ProjectVersion = version;
            Organization   = organization;

            CmdLineProperties         = cmdLineProperties ?? throw new ArgumentNullException("cmdLineProperties");
            this.globalFileProperties = globalFileProperties ?? throw new ArgumentNullException("globalFileProperties");
            ScannerEnvProperties      = scannerEnvProperties ?? throw new ArgumentNullException("scannerEnvProperties");
            InstallLoaderTargets      = installLoaderTargets;

            AggregateProperties = new AggregatePropertiesProvider(cmdLineProperties, globalFileProperties, ScannerEnvProperties);
            if (!AggregateProperties.TryGetValue(SonarProperties.HostUrl, out sonarQubeUrl))
            {
                sonarQubeUrl = "http://localhost:9000";
            }
        }
        /// <summary>
        /// Attempts to process the supplied command line arguments and
        /// reports any errors using the logger.
        /// Returns false if any parsing errors were encountered.
        /// </summary>
        public static bool TryProcessArgs(string[] commandLineArgs, ILogger logger, out IAnalysisPropertyProvider provider)
        {
            if (commandLineArgs == null)
            {
                throw new ArgumentNullException("commandLineArgs");
            }
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            provider = null;
            IEnumerable<ArgumentInstance> arguments;

            // This call will fail if there are duplicate or missing arguments
            CommandLineParser parser = new CommandLineParser(Descriptors, false /* don't allow unrecognized arguments*/);
            bool parsedOk = parser.ParseArguments(commandLineArgs, logger, out arguments);

            if (parsedOk)
            {
                // Handler for command line analysis properties
                parsedOk &= CmdLineArgPropertyProvider.TryCreateProvider(arguments, logger, out provider);

                Debug.Assert(!parsedOk || provider != null);

                if (parsedOk && !AreParsedArgumentsValid(provider, logger))
                {
                    provider = null;
                }
            }

            return provider != null;
        }
Example #15
0
        public static void AssertExpectedPropertyValue(this IAnalysisPropertyProvider provider, string key, string expectedValue)
        {
            var found = provider.TryGetProperty(key, out Property property);

            found.Should().BeTrue("Expected property was not found. Key: {0}", key);
            property.Value.Should().Be(expectedValue, "");
        }
        /// <summary>
        /// Generates several files related to rulesets and roslyn analyzer assemblies.
        /// Active rules should never be empty, but depending on the server settings of repo keys, we might have no rules in the ruleset.
        /// In that case, this method returns null.
        /// </summary>
        public AnalyzerSettings SetupAnalyzer(TeamBuildSettings teamBuildSettings, IAnalysisPropertyProvider sonarProperties,
                                              IEnumerable <SonarRule> activeRules, IEnumerable <SonarRule> inactiveRules, string language)
        {
            this.teamBuildSettings = teamBuildSettings ?? throw new ArgumentNullException(nameof(teamBuildSettings));
            this.sonarProperties   = sonarProperties ?? throw new ArgumentNullException(nameof(sonarProperties));

            if (language == null)
            {
                throw new ArgumentNullException(nameof(language));
            }

            if (inactiveRules == null)
            {
                throw new ArgumentNullException(nameof(inactiveRules));
            }

            if (activeRules == null)
            {
                throw new ArgumentNullException(nameof(activeRules));
            }

            var rulesetFilePath            = CreateRuleSet(language, activeRules, inactiveRules, ProjectType.Product);
            var testProjectRuleSetFilePath = CreateRuleSet(language, activeRules, inactiveRules, ProjectType.Test);
            var analyzerPlugins            = FetchAnalyzerPlugins(language, activeRules);
            var additionalFiles            = WriteAdditionalFiles(language, activeRules);

            return(new AnalyzerSettings(language, rulesetFilePath, testProjectRuleSetFilePath, analyzerPlugins, additionalFiles));
        }
        private static void AssertExpectedPropertiesFile(string expectedFilePath, IAnalysisPropertyProvider actualProvider)
        {
            var fileProvider = AssertIsFilePropertyProvider(actualProvider);

            fileProvider.PropertiesFile.Should().NotBeNull("Properties file object should not be null");
            fileProvider.PropertiesFile.FilePath.Should().Be(expectedFilePath, "Properties were not loaded from the expected location");
        }
        private static FilePropertyProvider AssertIsFilePropertyProvider(IAnalysisPropertyProvider actualProvider)
        {
            actualProvider.Should().NotBeNull("Supplied provider should not be null");
            actualProvider.Should().BeOfType <FilePropertyProvider>("Expecting a file provider");

            return((FilePropertyProvider)actualProvider);
        }
Example #19
0
        public void ConfigExt_GetAnalysisSettings_ServerOnly()
        {
            // Check that local settings are only retrieved by GetAnalysisSettings
            // if includeServerSettings is true

            // 0. Setup
            AnalysisConfig config = new AnalysisConfig
            {
                ServerSettings = new AnalysisProperties()
            };

            config.ServerSettings.Add(new Property()
            {
                Id = "server.1", Value = "server.value.1"
            });
            config.ServerSettings.Add(new Property()
            {
                Id = "server.2", Value = "server.value.2"
            });

            // 1. Local only
            IAnalysisPropertyProvider localProperties = config.GetAnalysisSettings(false);

            localProperties.AssertExpectedPropertyCount(0);

            localProperties.AssertPropertyDoesNotExist("server.1");
            localProperties.AssertPropertyDoesNotExist("server.2");

            // 2. Local and server
            IAnalysisPropertyProvider allProperties = config.GetAnalysisSettings(true);

            allProperties.AssertExpectedPropertyCount(2);
            allProperties.AssertExpectedPropertyValue("server.1", "server.value.1");
            allProperties.AssertExpectedPropertyValue("server.2", "server.value.2");
        }
Example #20
0
        /// <summary>
        /// Attempts to construct and return a provider that uses analysis properties provided on the command line
        /// </summary>
        /// <param name="commandLineArguments">List of command line arguments (optional)</param>
        /// <returns>False if errors occurred when constructing the provider, otherwise true</returns>
        /// <remarks>If no properties were provided on the command line then an empty provider will be returned</remarks>
        public static bool TryCreateProvider(IEnumerable <ArgumentInstance> commandLineArguments, ILogger logger,
                                             out IAnalysisPropertyProvider provider)
        {
            if (commandLineArguments == null)
            {
                throw new ArgumentNullException(nameof(commandLineArguments));
            }
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            if (ExtractAndValidateProperties(commandLineArguments, logger, out var validProperties))
            {
                if (validProperties.Any())
                {
                    provider = new CmdLineArgPropertyProvider(validProperties);
                }
                else
                {
                    provider = EmptyPropertyProvider.Instance;
                }

                return(true);
            }

            provider = null;
            return(false);
        }
        /// <summary>
        /// Attempts to process the supplied command line arguments and
        /// reports any errors using the logger.
        /// Returns false if any parsing errors were encountered.
        /// </summary>
        public static bool TryProcessArgs(string[] commandLineArgs, ILogger logger, out IAnalysisPropertyProvider provider)
        {
            if (commandLineArgs == null)
            {
                throw new ArgumentNullException(nameof(commandLineArgs));
            }
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            provider = null;

            // This call will fail if there are duplicate or missing arguments
            var parser   = new CommandLineParser(Descriptors, false /* don't allow unrecognized arguments*/);
            var parsedOk = parser.ParseArguments(commandLineArgs, logger, out IEnumerable <ArgumentInstance> arguments);

            if (parsedOk)
            {
                // Handler for command line analysis properties
                parsedOk &= CmdLineArgPropertyProvider.TryCreateProvider(arguments, logger, out provider);

                Debug.Assert(!parsedOk || provider != null);

                if (parsedOk && !AreParsedArgumentsValid(provider, logger))
                {
                    provider = null;
                }
            }

            return(provider != null);
        }
        public static void AssertPropertyDoesNotExist(this IAnalysisPropertyProvider provider, string key)
        {
            Property property;
            bool     found = provider.TryGetProperty(key, out property);

            Assert.IsFalse(found, "Not expecting the property to exist. Key: {0}, value: {1}", key);
        }
        private ProjectInfoAnalysisResult InvokeSonarScanner(IAnalysisPropertyProvider cmdLineArgs, AnalysisConfig config, ILogger logger)
        {
            IEnumerable <string> args = GetSonarScannerArgs(cmdLineArgs);

            logger.IncludeTimestamp = false;
            ProjectInfoAnalysisResult result = this.sonarScanner.Execute(config, args, logger);

            logger.IncludeTimestamp = true;
            return(result);
        }
Example #24
0
        private ProjectInfoAnalysisResult InvokeSonarScanner(IAnalysisPropertyProvider cmdLineArgs, AnalysisConfig config)
        {
            var args = GetSonarScannerArgs(cmdLineArgs);

            logger.IncludeTimestamp = false;
            var result = sonarScanner.Execute(config, args, logger);

            logger.IncludeTimestamp = true;
            return(result);
        }
        AnalyzerSettings IAnalyzerProvider.SetupAnalyzer(TeamBuildSettings teamBuildSettings, IAnalysisPropertyProvider sonarProperties, IEnumerable <SonarRule> rules, string language)
        {
            teamBuildSettings.Should().NotBeNull();
            sonarProperties.Should().NotBeNull();
            language.Should().NotBeNullOrWhiteSpace();

            SuppliedSonarProperties = sonarProperties;

            return(SettingsToReturn);
        }
        private bool InvokeSonarScanner(IAnalysisPropertyProvider cmdLineArgs, AnalysisConfig config, String propertiesFilePath)
        {
            var args = GetSonarScannerArgs(cmdLineArgs);

            logger.IncludeTimestamp = false;
            var result = sonarScanner.Execute(config, args, propertiesFilePath);

            logger.IncludeTimestamp = true;
            return(result);
        }
        private static string FindBranch(AnalysisConfig config)
        {
            IAnalysisPropertyProvider localSettings = config.GetAnalysisSettings(includeServerSettings: false);

            Debug.Assert(localSettings != null);

            localSettings.TryGetValue(SonarProperties.ProjectBranch, out string branch);

            return(branch);
        }
Example #28
0
        public static string GenerateXml(IEnumerable <SonarRule> activeRules, IAnalysisPropertyProvider analysisProperties,
                                         string language)
        {
            var repoKey = language.Equals(RoslynAnalyzerProvider.CSharpLanguage) ? "csharpsquid" : "vbnet";

            var repoActiveRules = activeRules.Where(ar => repoKey.Equals(ar.RepoKey));
            var settings        = analysisProperties.GetAllProperties().Where(a => a.Id.StartsWith("sonar." + language + "."));

            var builder = new StringBuilder();

            builder.AppendLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            builder.AppendLine("<AnalysisInput>");

            builder.AppendLine("  <Settings>");
            foreach (var pair in settings)
            {
                if (!Utilities.IsSecuredServerProperty(pair.Id))
                {
                    WriteSetting(builder, pair.Id, pair.Value);
                }
            }
            builder.AppendLine("  </Settings>");

            builder.AppendLine("  <Rules>");

            foreach (var activeRule in repoActiveRules)
            {
                builder.AppendLine("    <Rule>");
                var templateKey = activeRule.TemplateKey;
                var ruleKey     = templateKey ?? activeRule.RuleKey;
                builder.AppendLine("      <Key>" + EscapeXml(ruleKey) + "</Key>");

                if (activeRule.Parameters != null && activeRule.Parameters.Any())
                {
                    builder.AppendLine("      <Parameters>");
                    foreach (var entry in activeRule.Parameters)
                    {
                        builder.AppendLine("        <Parameter>");
                        builder.AppendLine("          <Key>" + EscapeXml(entry.Key) + "</Key>");
                        builder.AppendLine("          <Value>" + EscapeXml(entry.Value) + "</Value>");
                        builder.AppendLine("        </Parameter>");
                    }
                    builder.AppendLine("      </Parameters>");
                }
                builder.AppendLine("    </Rule>");
            }

            builder.AppendLine("  </Rules>");

            builder.AppendLine("  <Files>");
            builder.AppendLine("  </Files>");
            builder.AppendLine("</AnalysisInput>");

            return(builder.ToString());
        }
        private static string TryGetHostUrl(IAnalysisPropertyProvider properties, ILogger logger)
        {
            string url;

            if (properties.TryGetValue(SonarProperties.HostUrl, out url))
            {
                return(url);
            }

            logger.LogError(Resources.ERROR_Args_UrlRequired);
            return(null);
        }
Example #30
0
        public static bool HasProperty(this IAnalysisPropertyProvider provider, string key)
        {
            if (provider == null)
            {
                throw new ArgumentNullException(nameof(provider));
            }
            if (string.IsNullOrWhiteSpace(key))
            {
                throw new ArgumentNullException(nameof(key));
            }

            return(provider.TryGetProperty(key, out var _));
        }
Example #31
0
        public void SonarProjectBaseDir_IsAllowed()
        {
            TestLogger logger             = new TestLogger();
            IList <ArgumentInstance> args = new List <ArgumentInstance>();

            // sonar.projectBaseDir used to be un-settable
            AddDynamicArguments(args, "sonar.projectBaseDir=value1");

            IAnalysisPropertyProvider provider = CheckProcessingSucceeds(args, logger);

            provider.AssertExpectedPropertyValue("sonar.projectBaseDir", "value1");
            provider.AssertExpectedPropertyCount(1);
        }
        /// <summary>
        /// Credentials must be passed to both begin and end step (or not passed at all). If the credentials are passed to only
        /// one of the steps the analysis will fail so let's fail-fast with an explicit message.
        /// </summary>
        private bool CheckCredentialsInCommandLineArgs(AnalysisConfig config, IAnalysisPropertyProvider provider)
        {
            var hasCredentialsInBeginStep = config.HasBeginStepCommandLineCredentials;
            var hasCredentialsInEndStep   = provider.TryGetProperty(SonarProperties.SonarUserName, out var _);

            if (hasCredentialsInBeginStep ^ hasCredentialsInEndStep)
            {
                logger.LogError(Resources.ERROR_CredentialsNotSpecified);
                return(false);
            }

            return(true);
        }
 public static bool TryCreateProvider(ILogger logger, out IAnalysisPropertyProvider provider)
 {
     provider = null;
     try
     {
         provider = new EnvScannerPropertiesProvider(Environment.GetEnvironmentVariable(ENV_VAR_KEY));
         return(true);
     }
     catch (Exception)
     {
         logger?.LogError(Resources.ERROR_FailedParsePropertiesEnvVar, ENV_VAR_KEY);
     }
     return(false);
 }
        /// <summary>
        /// Computes verbosity based on the available properties. 
        /// </summary>
        /// <remarks>If no verbosity setting is present, the default verbosity (info) is used</remarks>
        public static LoggerVerbosity ComputeVerbosity(IAnalysisPropertyProvider properties, ILogger logger)
        {
            if (properties == null)
            {
                throw new ArgumentNullException("properties");
            }

            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            string sonarVerboseValue;
            properties.TryGetValue(SonarProperties.Verbose, out sonarVerboseValue);

            string sonarLogLevelValue;
            properties.TryGetValue(SonarProperties.LogLevel, out sonarLogLevelValue);

            return ComputeVerbosity(sonarVerboseValue, sonarLogLevelValue, logger);
        }
        /// <summary>
        /// Attempts to construct and return a file-based properties provider
        /// </summary>
        /// <param name="defaultPropertiesFileDirectory">Directory in which to look for the default properties file (optional)</param>
        /// <param name="commandLineArguments">List of command line arguments (optional)</param>
        /// <returns>False if errors occurred when constructing the provider, otherwise true</returns>
        /// <remarks>If a properties file could not be located then an empty provider will be returned</remarks>
        public static bool TryCreateProvider(IEnumerable<ArgumentInstance> commandLineArguments, string defaultPropertiesFileDirectory, ILogger logger, out IAnalysisPropertyProvider provider)
        {
            if (commandLineArguments == null)
            {
                throw new ArgumentNullException("commandLineArguments");
            }
            if (string.IsNullOrWhiteSpace(defaultPropertiesFileDirectory))
            {
                throw new ArgumentNullException("defaultDirectory");
            }
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            // If the path to a properties file was specified on the command line, use that.
            // Otherwise, look for a default properties file in the default directory.
            string propertiesFilePath;
            bool settingsFileArgExists = ArgumentInstance.TryGetArgumentValue(DescriptorId, commandLineArguments, out propertiesFilePath);

            AnalysisProperties locatedPropertiesFile;
            if (ResolveFilePath(propertiesFilePath, defaultPropertiesFileDirectory, logger, out locatedPropertiesFile))
            {
                if (locatedPropertiesFile == null)
                {
                    provider = EmptyPropertyProvider.Instance;
                }
                else
                {
                    provider = new FilePropertyProvider(locatedPropertiesFile, !settingsFileArgExists);
                }
                return true;
            }

            provider = null;
            return false;
        }
        private static string TryGetHostUrl(IAnalysisPropertyProvider properties, ILogger logger)
        {
            string url;
            if (properties.TryGetValue(SonarProperties.HostUrl, out url))
            {
                return url;
            }

            logger.LogError(Resources.ERROR_Args_UrlRequired);
            return null;
        }
        private static void AssertExpectedPropertiesFile(string expectedFilePath, IAnalysisPropertyProvider actualProvider)
        {
            FilePropertyProvider fileProvider = AssertIsFilePropertyProvider(actualProvider);

            Assert.IsNotNull(fileProvider.PropertiesFile, "Properties file object should not be null");
            Assert.AreEqual(expectedFilePath, fileProvider.PropertiesFile.FilePath, "Properties were not loaded from the expected location");
        }
 private static void AssertIsNotDefaultPropertiesFile(IAnalysisPropertyProvider actualProvider)
 {
     FilePropertyProvider fileProvider = AssertIsFilePropertyProvider(actualProvider);
     Assert.IsFalse(fileProvider.IsDefaultSettingsFile, "Not expecting the provider to be marked as using the default properties file");
 }
        private static FilePropertyProvider AssertIsFilePropertyProvider(IAnalysisPropertyProvider actualProvider)
        {
            Assert.IsNotNull(actualProvider, "Supplied provider should not be null");
            Assert.IsInstanceOfType(actualProvider, typeof(FilePropertyProvider), "Expecting a file provider");

            return (FilePropertyProvider)actualProvider;
        }
        /// <summary>
        /// Performs any additional validation on the parsed arguments and logs errors
        /// if necessary.
        /// </summary>
        /// <returns>True if the arguments are valid, otherwise false</returns>
        private static bool AreParsedArgumentsValid(IAnalysisPropertyProvider provider, ILogger logger)
        {
            bool areValid = true;

            foreach (Property property in provider.GetAllProperties())
            {
                if (!IsPermittedProperty(property))
                {
                    areValid = false;
                    logger.LogError(Resources.ERROR_CmdLine_DisallowedArgument, property.Id);
                }
            }

            return areValid;
        }
        private static IEnumerable<string> GetSonarRunnerArgs(IAnalysisPropertyProvider provider)
        {
            IList<string> args = new List<string>();

            if (provider != null)
            {
                foreach (Property property in provider.GetAllProperties())
                {
                    args.Add(property.AsSonarRunnerArg());
                }
            }

            return args;
        }
        private static IBootstrapperSettings CreatePostProcessorSettings(IList<string> childArgs, IAnalysisPropertyProvider properties, ILogger logger)
        {
            IBootstrapperSettings settings = new BootstrapperSettings(
                AnalysisPhase.PostProcessing,
                childArgs,
                string.Empty,
                VerbosityCalculator.ComputeVerbosity(properties, logger),
                logger);

            return settings;
        }
        private ProjectInfoAnalysisResult InvokeSonarRunner(IAnalysisPropertyProvider cmdLineArgs, AnalysisConfig config, ILogger logger)
        {
            IEnumerable<string> args = GetSonarRunnerArgs(cmdLineArgs);

            logger.IncludeTimestamp = false;
            ProjectInfoAnalysisResult result = this.sonarRunner.Execute(config, args, logger);
            logger.IncludeTimestamp = true;
            return result;
        }
        private static IBootstrapperSettings CreatePreProcessorSettings(IList<string> childArgs, IAnalysisPropertyProvider properties, IAnalysisPropertyProvider globalFileProperties, ILogger logger)
        {
            string hostUrl = TryGetHostUrl(properties, logger);
            if (hostUrl == null)
            {
                return null; // URL is a required parameter in the pre-process phase
            }

            // If we're using the default properties file then we need to pass it
            // explicitly to the pre-processor (it's in a different folder and won't
            // be able to find it otherwise).
            FilePropertyProvider fileProvider = globalFileProperties as FilePropertyProvider;
            if (fileProvider != null && fileProvider.IsDefaultSettingsFile)
            {
                Debug.Assert(fileProvider.PropertiesFile != null);
                Debug.Assert(!string.IsNullOrEmpty(fileProvider.PropertiesFile.FilePath), "Expecting the properties file path to be set");
                childArgs.Add(string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}\"{1}\"", FilePropertyProvider.Prefix, fileProvider.PropertiesFile.FilePath));
            }

            IBootstrapperSettings settings = new BootstrapperSettings(
                AnalysisPhase.PreProcessing,
                childArgs,
                hostUrl,
                VerbosityCalculator.ComputeVerbosity(properties, logger),
                logger);

            return settings;
        }
        /// <summary>
        /// Performs any additional validation on the parsed arguments and logs errors
        /// if necessary.
        /// </summary>
        /// <returns>True if the arguments are valid, otherwise false</returns>
        private static bool AreParsedArgumentsValid(IAnalysisPropertyProvider provider, ILogger logger)
        {
            return true;

            // SONARMSBRU-136/SONARMSBRU-137: back-compat with v1.0 - allow sensitive data to be stored in the generated project properties file and config file.
            // SONARMSBRU-136: TODO - uncomment the following code:
            //bool areValid = true;

            //// Only sensitive data arguments are allowed on the post-processor command line
            //foreach(Property property in provider.GetAllProperties())
            //{
            //    if (!IsPermittedProperty(property))
            //    {
            //        areValid = false;
            //        logger.LogError(Resources.ERROR_CmdLine_DisallowedArgument, property.Id);
            //    }
            //}

            //return areValid;
        }