Exemplo n.º 1
0
    public bool Execute()
    {
        var executingMessage = string.Format("Fody (version {0}) Executing", typeof (Processor).Assembly.GetName().Version);
        BuildEngine.LogMessageEvent(new BuildMessageEventArgs(executingMessage, "", "Fody", MSMessageEnum.High));

        var stopwatch = Stopwatch.StartNew();

        Logger = new BuildLogger(MessageImportance)
                     {
                         BuildEngine = BuildEngine,
                     };

        try
        {
            Inner();
            return !Logger.ErrorOccurred;
        }
        catch (Exception exception)
        {
            Logger.LogError(exception.ToFriendlyString());
            return false;
        }
        finally
        {
            var finishedMessage = string.Format("\tFinished Fody {0}ms.", stopwatch.ElapsedMilliseconds);
            Logger.Flush();
            BuildEngine.LogMessageEvent(new BuildMessageEventArgs(finishedMessage, "", "Fody", MSMessageEnum.High));
        }
    }
        public void Roslyn_Settings_ValidSetup()
        {
            // Arrange
            BuildLogger logger = new BuildLogger();
            ProjectRootElement projectRoot = CreateValidProjectSetup(null);

            // Add analyzer settings that should be removed
            projectRoot.AddItem(TargetProperties.AnalyzerItemType, "Analyzer1.dll");
            projectRoot.AddItem(TargetProperties.AnalyzerItemType, "c:\\Analyzer2.dll");

            projectRoot.AddItem(TargetProperties.AdditionalFilesItemType, "additional1.txt");
            projectRoot.AddItem(TargetProperties.AdditionalFilesItemType, "additional2.txt");

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger, TargetConstants.OverrideRoslynAnalysisTarget);

            // Assert
            logger.AssertTargetExecuted(TargetConstants.OverrideRoslynAnalysisTarget);
            logger.AssertTargetExecuted(TargetConstants.SetRoslynAnalysisPropertiesTarget);
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.OverrideRoslynAnalysisTarget);

            // Check the intermediate working properties have the expected values
            BuildAssertions.AssertExpectedPropertyValue(result.ProjectStateAfterBuild, "SonarQubeRoslynRulesetExists", "True");
            BuildAssertions.AssertExpectedPropertyValue(result.ProjectStateAfterBuild, "SonarQubeRoslynAssemblyExists", "True");
            BuildAssertions.AssertExpectedPropertyValue(result.ProjectStateAfterBuild, "SonarLintFound", "true");

            // Check the error log and ruleset properties are set
            string targetDir = result.ProjectStateAfterBuild.GetPropertyValue(TargetProperties.TargetDir);
            string expectedErrorLog = Path.Combine(targetDir, ErrorLogFileName);
            AssertExpectedAnalysisProperties(result, expectedErrorLog, GetDummyRulesetFilePath(), GetDummySonarLintXmlFilePath());
            AssertExpectedItemValuesExists(result, TargetProperties.AnalyzerItemType, GetSonarLintAnalyzerFilePaths());

            BuildAssertions.AssertWarningsAreNotTreatedAsErrorsNorIgnored(result);
        }
        public void E2E_FxCop_OutputFolderNotSet()
        {
            // Arrange
            string rootInputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Inputs");
            string rootOutputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Outputs");

            // Don't set the output folder
            WellKnownProjectProperties preImportProperties = new WellKnownProjectProperties();

            // Clear all of the variables that could be used to look up the output path
            // (necessary so the test works correctly when run under TeamBuild on a machine
            // that has the integration targets installed)
            preImportProperties.SonarQubeOutputPath = "";
            preImportProperties.TeamBuild2105BuildDirectory = "";
            preImportProperties.TeamBuildLegacyBuildDirectory = "";
            
            ProjectRootElement projectRoot = BuildUtilities.CreateValidProjectRoot(this.TestContext, rootInputFolder, preImportProperties);

            BuildLogger logger = new BuildLogger();

            // 1. No code analysis properties
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger);
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.DefaultBuildTarget);

            logger.AssertTargetNotExecuted(TargetConstants.OverrideFxCopSettingsTarget);
            logger.AssertTargetNotExecuted(TargetConstants.SetFxCopResultsTarget);

            AssertFxCopNotExecuted(logger);

            ProjectInfoAssertions.AssertNoProjectInfoFilesExists(rootOutputFolder);
        }
        public void StyleCop_TargetExecutionOrder()
        {
            // Arrange
            string rootInputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Inputs");
            string rootOutputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Outputs");

            WellKnownProjectProperties properties = new WellKnownProjectProperties();
            properties.SonarQubeTempPath = rootInputFolder;
            properties.SonarQubeOutputPath = rootInputFolder;
            properties.SonarQubeConfigPath = rootOutputFolder;

            ProjectRootElement projectRoot = BuildUtilities.CreateValidProjectRoot(this.TestContext, rootInputFolder, properties);

            // Add some settings we expect to be ignored
            AddAnalysisSetting("sonar.other.setting", "other value", projectRoot);
            AddAnalysisSetting("sonar.other.setting.2", "other value 2", projectRoot);
            projectRoot.Save();

            BuildLogger logger = new BuildLogger();

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger, TargetConstants.DefaultBuildTarget);

            // Assert
            logger.AssertTargetExecuted(TargetConstants.SetStyleCopSettingsTarget);
            logger.AssertExpectedTargetOrdering(TargetConstants.SetStyleCopSettingsTarget, TargetConstants.WriteProjectDataTarget);

            AssertExpectedStyleCopSetting(projectRoot.ProjectFileLocation.File, result);
        }
        public override bool Execute()
        {
            logger = new BuildLogger(BuildEngine);
            logger.LogInfo($"ScriptBuilderTask (version {typeof(ScriptBuilderTask).Assembly.GetName().Version}) Executing");

            var stopwatch = Stopwatch.StartNew();

            try
            {
                if (!ValidateInputs())
                {
                    return false;
                }
                Inner();
            }
            catch (ErrorsException exception)
            {
                logger.LogError(exception.Message, exception.FileName);
            }
            catch (Exception exception)
            {
                logger.LogError(exception.ToFriendlyString());
            }
            finally
            {
                logger.LogInfo($"  Finished ScriptBuilderTask {stopwatch.ElapsedMilliseconds}ms.");
            }
            return !logger.ErrorOccurred;
        }
Exemplo n.º 6
0
    public bool Execute()
    {
        BuildEngine.LogMessageEvent(new BuildMessageEventArgs(string.Format("Fody (version {0}) Executing", GetType().Assembly.GetName().Version), "", "Fody", Microsoft.Build.Framework.MessageImportance.High));

        var stopwatch = Stopwatch.StartNew();

        Logger = new BuildLogger(MessageImportance)
                     {
                         BuildEngine = BuildEngine,
                     };

        try
        {
            Inner();
            return !Logger.ErrorOccurred;
        }
        catch (Exception exception)
        {
            Logger.LogError(exception.ToFriendlyString());
            return false;
        }
        finally
        {
            stopwatch.Stop();
            Logger.Flush();
            BuildEngine.LogMessageEvent(new BuildMessageEventArgs(string.Format("\tFinished Fody {0}ms.", stopwatch.ElapsedMilliseconds), "", "Fody", Microsoft.Build.Framework.MessageImportance.High));
        }
    }
        public void ImportsBefore_SonarQubeTargetsPathNotSet()
        {
            // 1. Prebuild
            // Arrange
            this.EnsureDummyIntegrationTargetsFileExists();

            WellKnownProjectProperties preImportProperties = new WellKnownProjectProperties();
            preImportProperties.SonarQubeTargetsPath = "";
            preImportProperties.TeamBuild2105BuildDirectory = "";
            preImportProperties.TeamBuildLegacyBuildDirectory = "";

            // Act
            ProjectInstance projectInstance = this.CreateAndEvaluateProject(preImportProperties);

            // Assert
            BuildAssertions.AssertPropertyDoesNotExist(projectInstance, TargetProperties.SonarQubeTargetFilePath);
            AssertAnalysisTargetsAreNotImported(projectInstance);


            // 2. Now build -> succeeds. Info target not executed
            BuildLogger logger = new BuildLogger();

            BuildResult result = BuildUtilities.BuildTargets(projectInstance, logger);

            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.DefaultBuildTarget);
            logger.AssertTargetNotExecuted(TargetConstants.ImportBeforeInfoTarget);
            logger.AssertExpectedErrorCount(0);
        }
        public void E2E_FxCop_FailIfEnabledButNotInstalled()
        {
            string rootInputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Inputs");
            string rootOutputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Outputs");
            WellKnownProjectProperties preImportProperties = new WellKnownProjectProperties();
            preImportProperties.SonarQubeTempPath = rootOutputFolder;
            preImportProperties.SonarQubeOutputPath = rootOutputFolder;
            preImportProperties.SonarQubeConfigPath = rootInputFolder;

            // FxCop's targets is imported when Visual Studio is installed, see Microsoft.Common.CurrentVersion.targets
            preImportProperties["CodeAnalysisTargets"] = Path.Combine(rootInputFolder, "non-existing.targets");

            CreateValidFxCopRuleset(rootInputFolder, string.Format(TargetProperties.SonarQubeRulesetFormat, "cs"));

            ProjectRootElement projectRoot = BuildUtilities.CreateValidProjectRoot(this.TestContext, rootInputFolder, preImportProperties);

            BuildLogger logger = new BuildLogger();

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger);

            // Assert
            BuildAssertions.AssertTargetFailed(result, TargetConstants.DefaultBuildTarget);

            logger.AssertExpectedTargetOrdering(
                TargetConstants.DetectFxCopRulesetTarget,
                TargetConstants.FailIfFxCopNotInstalledTarget);

            AssertFxCopNotExecuted(logger);
        }
Exemplo n.º 9
0
    //-------------------------------------------------------------------------------------------------------------------------
    public static void Build(string config, string log_filename, BuildTarget target, string output)
    {
        BuildLogger logger = new BuildLogger(log_filename, false);

        logger.Log("Building Platform: " + target.ToString());
        logger.Log("Building Config:   " + config);
        logger.Log("");

        string[] level_list = FindScenes();
        logger.Log("Scenes to be processed: " + level_list.Length);

        foreach (string s in level_list)
        {
            string cutdown_level_name = s.Remove(s.IndexOf(".unity"));
            logger.Log("   " + cutdown_level_name);
        }

        // Make sure the paths exist before building.
        try
        {
            Directory.CreateDirectory(output);
        }
        catch
        {
            logger.Log("Failed to create directories: " + output);
        }

        string results = "";

        try
        {
            results = BuildPipeline.BuildPlayer(level_list, output, target, BuildOptions.None);
        }
        catch
        {
            logger.Log("Errors Found.");
            logger.Log(results);
            logger.Close();
        }

        logger.Log("");

        if (results.Length == 0)
            logger.Log("No Build Errors");
        else
        {
            logger.Log("Errors Found.");
            logger.Log(results);
        }

        logger.Close();
    }
        public void Roslyn_Settings_ValidSetup()
        {
            // Arrange
            BuildLogger logger = new BuildLogger();

            // Set the config directory so the targets know where to look for the analysis config file
            string confDir = TestUtils.CreateTestSpecificFolder(this.TestContext, "config");

            // Create a valid config file containing analyzer settings
            string[] expectedAssemblies = new string[] { "c:\\data\\config.analyzer1.dll", "c:\\config2.dll" };
            string[] expectedAdditionalFiles = new string[] { "c:\\config.1.txt", "c:\\config.2.txt" };

            AnalysisConfig config = new AnalysisConfig();
            config.AnalyzerSettings = new AnalyzerSettings();
            config.AnalyzerSettings.RuleSetFilePath = "d:\\my.ruleset";
            config.AnalyzerSettings.AnalyzerAssemblyPaths = expectedAssemblies.ToList();
            config.AnalyzerSettings.AdditionalFilePaths = expectedAdditionalFiles.ToList();
            string configFilePath = Path.Combine(confDir, FileConstants.ConfigFileName);
            config.Save(configFilePath);

            // Create the project
            WellKnownProjectProperties properties = new WellKnownProjectProperties();
            properties.SonarQubeConfigPath = confDir;
            properties.ResolvedCodeAnalysisRuleset = "c:\\should.be.overridden.ruleset";

            ProjectRootElement projectRoot = CreateValidProjectSetup(properties);

            projectRoot.AddItem(TargetProperties.AnalyzerItemType, "should.be.removed.analyzer1.dll");
            projectRoot.AddItem(TargetProperties.AnalyzerItemType, "c:\\should.be.removed.analyzer2.dll");
            projectRoot.AddItem(TargetProperties.AdditionalFilesItemType, "should.be.removed.additional1.txt");
            projectRoot.AddItem(TargetProperties.AdditionalFilesItemType, "should.be.removed.additional2.txt");

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger, TargetConstants.OverrideRoslynAnalysisTarget);

            // Assert
            logger.AssertTargetExecuted(TargetConstants.OverrideRoslynAnalysisTarget);
            logger.AssertTargetExecuted(TargetConstants.SetRoslynAnalysisPropertiesTarget);
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.OverrideRoslynAnalysisTarget);

            // Check the error log and ruleset properties are set
            AssertErrorLogIsSetBySonarQubeTargets(result);
            AssertExpectedResolvedRuleset(result, "d:\\my.ruleset");
            AssertExpectedItemValuesExists(result, TargetProperties.AdditionalFilesItemType, expectedAdditionalFiles);
            AssertExpectedItemValuesExists(result, TargetProperties.AnalyzerItemType, expectedAssemblies);

            BuildAssertions.AssertWarningsAreNotTreatedAsErrorsNorIgnored(result);
        }
        public void SQBeforeClCompile_DefaultBinPath_BinariesFound_TaskExecuted()
        {
            // Arrange
            string rootInputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Inputs");
            string rootOutputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Outputs");
            BuildLogger logger = new BuildLogger();

            WellKnownProjectProperties properties = new WellKnownProjectProperties();
            properties.SonarQubeTempPath = rootInputFolder;
            properties.BuildWrapperSkipFlag = "false";
            properties.SonarQubeOutputPath = rootOutputFolder;

            // By default, the targets try to find the build wrapper binaries in a specific folder
            // below the folder containing the integration tasks assembly

            ProjectRootElement projectRoot = BuildUtilities.CreateValidProjectRoot(this.TestContext, rootInputFolder, properties);

            // Check we can find the integration targets file in the expected location
            string targetsDir = TestUtils.GetTestSpecificFolderName(this.TestContext);
            string integrationTargetsPath = Path.Combine(targetsDir, TestUtils.AnalysisTargetFile);
            Assert.IsTrue(File.Exists(integrationTargetsPath), "Test setup error: did not find the integration targets in the expected location: {0}", integrationTargetsPath);

            // The targets expect to find the build wrapper binaries in a folder under
            // the folder containing the tasks assembly.
            // Create a dummy tasks assembly
            string dummyAsmFilePath = Path.Combine(targetsDir, "SonarQube.Integration.Tasks.dll");
            Assert.IsFalse(File.Exists(dummyAsmFilePath), "Test setup error: not expecting the integration tasks assembly to exist at {0}", dummyAsmFilePath);
            File.WriteAllText(dummyAsmFilePath, "dummy content");

            // Create the build wrapper sub directory
            string buildWrapperBinDir = Path.Combine(targetsDir, "build-wrapper-win-x86");
            Directory.CreateDirectory(buildWrapperBinDir);

            // Create the required build wrapper files relative to this location
            CreateBuildWrapperMarkerFile(buildWrapperBinDir);

            // Act
            BuildUtilities.BuildTargets(projectRoot, logger, TargetConstants.BuildWrapperBeforeClCompileTarget);

            // Assert
            logger.AssertTargetExecuted(TargetConstants.BuildWrapperBeforeClCompileTarget);
            logger.AssertTargetExecuted(TargetConstants.BuildWrapperAttachTarget);
            // Note: task should fail because not all required files are present. However,
            // the important thing for this test is that is executed.
            logger.AssertTaskExecuted(TargetConstants.BuildWrapperAttachTask);
        }
        public void E2E_FxCop_AllConditionsMet()
        {
            // Arrange
            string rootInputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Inputs");
            string rootOutputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Outputs");

            string fxCopLogFile = Path.Combine(rootInputFolder, "FxCopResults.xml");
            WellKnownProjectProperties preImportProperties = new WellKnownProjectProperties();
            preImportProperties.SonarQubeTempPath = rootOutputFolder; // FIXME
            preImportProperties.SonarQubeOutputPath = rootOutputFolder;
            preImportProperties.RunCodeAnalysis = "false";
            preImportProperties.CodeAnalysisLogFile = fxCopLogFile;
            preImportProperties.CodeAnalysisRuleset = "specifiedInProject.ruleset";

            preImportProperties[TargetProperties.SonarQubeConfigPath] = rootInputFolder;
            CreateValidFxCopRuleset(rootInputFolder, string.Format(TargetProperties.SonarQubeRulesetFormat, "cs"));

            ProjectRootElement projectRoot = BuildUtilities.CreateValidProjectRoot(this.TestContext, rootInputFolder, preImportProperties);

            string itemPath = TestUtils.CreateTextFile(rootInputFolder, "my.cs", "class myclass{}");
            projectRoot.AddItem(TargetProperties.ItemType_Compile, itemPath);
            projectRoot.Save();

            BuildLogger logger = new BuildLogger();

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger);

            // Assert
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.DefaultBuildTarget);

            logger.AssertExpectedTargetOrdering(
                TargetConstants.DetectFxCopRulesetTarget,
                TargetConstants.CategoriseProjectTarget,
                TargetConstants.OverrideFxCopSettingsTarget,
                TargetConstants.FxCopTarget,
                TargetConstants.SetFxCopResultsTarget,
                TargetConstants.DefaultBuildTarget);

            AssertAllFxCopTargetsExecuted(logger);
            Assert.IsTrue(File.Exists(fxCopLogFile), "FxCop log file should have been produced");

            ProjectInfo projectInfo = ProjectInfoAssertions.AssertProjectInfoExists(rootOutputFolder, projectRoot.FullPath);
            ProjectInfoAssertions.AssertAnalysisResultExists(projectInfo, AnalysisType.FxCop.ToString(), fxCopLogFile);
        }
        public void StyleCop_TempFolderIsNotSet()
        {
            // Arrange
            string rootInputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Inputs");

            WellKnownProjectProperties properties = new WellKnownProjectProperties();
            properties.SonarQubeTempPath = "";

            ProjectRootElement projectRoot = BuildUtilities.CreateValidProjectRoot(this.TestContext, rootInputFolder, properties);

            BuildLogger logger = new BuildLogger();

            // Act
            BuildUtilities.BuildTargets(projectRoot, logger, TargetConstants.SetStyleCopSettingsTarget);

            // Assert
            logger.AssertTargetNotExecuted(TargetConstants.SetStyleCopSettingsTarget);
        }
        public override BuildPipelineCodes Convert(GUID scene, BuildSettings settings, out SceneLoadInfo output)
        {
            StartProgressBar("Calculating Scene Dependencies", 1);
            if (!ValidScene(scene))
            {
                output = new SceneLoadInfo();
                EndProgressBar();
                return(BuildPipelineCodes.Error);
            }

            var scenePath = AssetDatabase.GUIDToAssetPath(scene.ToString());

            if (!UpdateProgressBar(scenePath))
            {
                output = new SceneLoadInfo();
                EndProgressBar();
                return(BuildPipelineCodes.Canceled);
            }

            Hash128 hash = CalculateInputHash(scene, settings);

            if (UseCache && BuildCache.TryLoadCachedResults(hash, out output))
            {
                if (!EndProgressBar())
                {
                    return(BuildPipelineCodes.Canceled);
                }
                return(BuildPipelineCodes.SuccessCached);
            }

            output = BundleBuildInterface.PrepareScene(scenePath, settings, GetBuildPath(hash));

            if (UseCache && !BuildCache.SaveCachedResults(hash, output))
            {
                BuildLogger.LogWarning("Unable to cache SceneDependency results for asset '{0}'.", scene);
            }

            if (!EndProgressBar())
            {
                return(BuildPipelineCodes.Canceled);
            }
            return(BuildPipelineCodes.Success);
        }
Exemplo n.º 15
0
        /// <summary>
        /// 取得输出目录.
        /// </summary>
        /// <returns>The output dir.</returns>
        /// <param name="iTarget">打包目标类型.</param>
        /// <param name="iOutputDir">输出目录(未指定:默认输出根目录).</param>
        private static string GetOutputDir(BuildTarget iTarget, string iOutputDir = null)
        {
            string outputRootDir = iOutputDir;

            if (string.IsNullOrEmpty(outputRootDir) == true)
            {
                outputRootDir = _defaultOutputRootDir;
            }

            if (Directory.Exists(outputRootDir) == false)
            {
                BuildLogger.LogWarning("The directory is not exist, so to create.(dir:{0})",
                                       outputRootDir);
                Directory.CreateDirectory(outputRootDir);
            }
            if (Directory.Exists(outputRootDir) == false)
            {
                BuildLogger.LogError("[Directory Create Failed] -> Dir:{0}", outputRootDir);
                return(null);
            }
            else
            {
                BuildLogger.LogMessage("[Directory Create Successed] -> Dir:{0}", outputRootDir);
            }
            string outputDir = string.Format("{0}/{1}", outputRootDir, iTarget.ToString());

            if (Directory.Exists(outputDir) == false)
            {
                BuildLogger.LogWarning("The directory is not exist, so to create.(dir:{0})",
                                       outputDir);
                Directory.CreateDirectory(outputDir);
            }
            if (Directory.Exists(outputDir) == false)
            {
                BuildLogger.LogError("[Directory Create Failed] -> Dir:{0}", outputDir);
                return(null);
            }
            else
            {
                BuildLogger.LogMessage("[Directory Create Successed] -> Dir:{0}", outputDir);
            }
            return(outputDir);
        }
Exemplo n.º 16
0
        static void BuildForAndroid()
        {
            const string funcBlock = "AssetBundlesBuild.BuildForAndroid()";

            BuildLogger.OpenBlock(funcBlock);

            // 开始打包Bundles
            UtilsAsset.StartBuildBundles();

            BuildAssetBundle(BuildTarget.Android, true);

            // 生成上传用的Shell
            CreateUploadShell();

            // 开始打包Bundles
            UtilsAsset.EndBuildBundles();

            BuildLogger.CloseBlock();
        }
        public void Roslyn_SetResults_ResultsFileDoesNotExist()
        {
            // Arrange
            string rootInputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Inputs");

            WellKnownProjectProperties properties = new WellKnownProjectProperties();
            properties.SonarQubeTempPath = rootInputFolder;

            ProjectRootElement projectRoot = BuildUtilities.CreateValidProjectRoot(this.TestContext, rootInputFolder, properties);

            BuildLogger logger = new BuildLogger();

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger, TargetConstants.SetRoslynResultsTarget);

            // Assert
            logger.AssertTargetExecuted(TargetConstants.SetRoslynResultsTarget);
            BuildAssertions.AssertAnalysisSettingDoesNotExist(result, RoslynAnalysisResultsSettingName);
        }
        public void E2E_MissingProjectGuid()
        {
            // Projects with missing guids should have a warning emitted. The project info
            // should not be generated.

            // Arrange
            string rootInputFolder  = TestUtils.CreateTestSpecificFolder(this.TestContext, "Inputs");
            string rootOutputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Outputs");

            WellKnownProjectProperties preImportProperties = CreateDefaultAnalysisProperties(rootInputFolder, rootOutputFolder);

            preImportProperties["SonarConfigPath"] = rootInputFolder;

            ProjectDescriptor descriptor = new ProjectDescriptor()
            {
                // No guid property
                IsTestProject       = false,
                ParentDirectoryPath = rootInputFolder,
                ProjectFolderName   = "MyProjectDir",
                ProjectFileName     = "MissingProjectGuidProject.proj"
            };

            AddEmptyAnalysedCodeFile(descriptor, rootInputFolder);

            ProjectRootElement projectRoot = BuildUtilities.CreateInitializedProjectRoot(this.TestContext, descriptor, preImportProperties);

            BuildLogger logger = new BuildLogger();

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger);

            // Assert
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.DefaultBuildTarget); // Build should succeed with warnings
            ProjectInfoAssertions.AssertNoProjectInfoFilesExists(rootOutputFolder);

            logger.AssertExpectedErrorCount(0);
            logger.AssertExpectedWarningCount(1);

            BuildWarningEventArgs warning = logger.Warnings[0];

            Assert.IsTrue(warning.Message.Contains(descriptor.FullFilePath),
                          "Expecting the warning to contain the full path to the bad project file");
        }
Exemplo n.º 19
0
        public void Roslyn_SetResults_TempFolderIsNotSet()
        {
            // Arrange
            string rootInputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Inputs");

            WellKnownProjectProperties properties = new WellKnownProjectProperties();

            properties.SonarQubeTempPath = "";

            ProjectRootElement projectRoot = BuildUtilities.CreateValidProjectRoot(this.TestContext, rootInputFolder, properties);

            BuildLogger logger = new BuildLogger();

            // Act
            BuildUtilities.BuildTargets(projectRoot, logger, TargetConstants.SetRoslynResultsTarget);

            // Assert
            logger.AssertTargetNotExecuted(TargetConstants.SetRoslynResultsTarget);
        }
Exemplo n.º 20
0
        private void ApplyExplicitInterfaceVisibility(
            XPathNavigator rootNavigator, BuildLogger logger)
        {
            if (_visibility.ExplicitInterfaceMembers)
            {
                return;
            }

            int itemCount = 0;

            XPathNodeIterator iterator = rootNavigator.Select(
                "api[memberdata/@visibility='private' and proceduredata/@virtual='true']");

            if (iterator != null && iterator.Count != 0)
            {
                XPathNavigator[] navigators = ToClonedArray(iterator);

                foreach (XPathNavigator navigator in navigators)
                {
                    navigator.DeleteSelf();
                    itemCount++;
                }
            }

            iterator = rootNavigator.Select(
                "api/elements/element[memberdata/@visibility='private' and proceduredata/@virtual='true']");
            if (iterator != null && iterator.Count != 0)
            {
                XPathNavigator[] navigators = ToClonedArray(iterator);

                foreach (XPathNavigator navigator in navigators)
                {
                    navigator.DeleteSelf();
                    itemCount++;
                }
            }

            if (itemCount > 0 && logger != null)
            {
                logger.WriteLine(itemCount.ToString().PadRight(5) +
                                 " Explicit interface implementations removed.", BuildLoggerLevel.Info);
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// 取得指定目录文件列表(包含子目录).
        /// </summary>
        /// <returns>文件列表.</returns>
        /// <param name="iDirection">文件目录.</param>
        static List <string> GetAllFiles(string iDirection)
        {
            List <string> filesList = new List <string>();

            try
            {
                bool isDir = false;
                if ((false == string.IsNullOrEmpty(iDirection)) &&
                    (true == iDirection.EndsWith("/")))
                {
                    isDir = true;
                }
                if (true == isDir)
                {
                    string[] files = Directory.GetFiles(iDirection, "*.*", SearchOption.AllDirectories);

                    foreach (string strVal in files)
                    {
                        if (string.IsNullOrEmpty(strVal))
                        {
                            continue;
                        }
                        if (strVal.EndsWith(".ds_store") == true)
                        {
                            continue;
                        }
                        filesList.Add(strVal);
                    }
                }
                else
                {
                    filesList.Add(iDirection);
                }
            }
            catch (System.IO.DirectoryNotFoundException exp)
            {
                BuildLogger.LogException("The Directory is not exist!!!(dir:{0} detail:{1})",
                                         iDirection, exp.Message);
            }

            return(filesList);
        }
Exemplo n.º 22
0
        public bool Run(BuildContext context)
        {
            _context = context;
            _logger  = context.Logger;

            BuildSettings settings = context.Settings;

            string dataDir = Path.Combine(_options.OutputDirectory, "Data");

            try
            {
                _plusTree = new PersistentDictionary <string, string>(dataDir);

                WriteHtmls();
                if (!WriteHhk())
                {
                    return(false);
                }
                if (!WriteToc())
                {
                    return(false);
                }

                return(true);
            }
            catch (Exception ex)
            {
                if (_logger != null)
                {
                    _logger.WriteLine(ex, BuildLoggerLevel.Error);
                }

                return(false);
            }
            finally
            {
                if (_plusTree != null)
                {
                    _plusTree.Dispose();
                }
            }
        }
Exemplo n.º 23
0
        protected override bool OnExecute(BuildContext context)
        {
            BuildLogger logger = context.Logger;

            if (String.IsNullOrEmpty(_webHelpFile) || !File.Exists(_webHelpFile))
            {
                if (logger != null)
                {
                    logger.WriteLine("The help file is not available.",
                                     BuildLoggerLevel.Error);
                }

                return(false);
            }

            if (logger != null)
            {
                logger.WriteLine("Opening: " + _webHelpFile, BuildLoggerLevel.Info);
            }

            try
            {
                Process process = Process.Start(_webHelpFile);
                // The return could be null, if no process resource is started
                // (for example, if an existing process is reused as in browsers).
                if (process != null)
                {
                    process.Close();
                }

                return(true);
            }
            catch (Exception ex)
            {
                if (logger != null)
                {
                    logger.WriteLine(ex, BuildLoggerLevel.Error);
                }

                return(true);
            }
        }
Exemplo n.º 24
0
        /// <summary>
        /// 打包前将非资源对象,移动到临时文件夹.
        /// </summary>
        public static void MoveUnResources()
        {
            const string funcBlock = "AssetBundle.MoveUnResources()";

            BuildLogger.OpenBlock(funcBlock);

//			AssetBundlesConfig bcConfig = AssetBundlesConfig.ReadConfig();
//
//			foreach(BundleUnResource urpi in bcConfig.UnResources)
//			{
//				bool isDir = false;
//				string dirName = "";
//				string allDirName = "";
//				if(urpi.Path.Contains(".") == false)
//				{
//					isDir = true;
//					int index = urpi.Path.LastIndexOf("/");
//					allDirName = urpi.Path.Substring(0, index);
//					index = allDirName.LastIndexOf("/");
//					dirName = allDirName.Substring(index + 1, allDirName.Length - index - 1);
//
//					string pathTempDir = Application.dataPath + unResourcesPathTempDir + dirName;
//					allDirName = allDirName.Replace("Assets/", "/");
//					allDirName = Application.dataPath + allDirName;
//
//					FileUtil.DeleteFileOrDirectory(allDirName);
//					FileUtil.DeleteFileOrDirectory(allDirName + ".meta");
//
//					//FileUtil.MoveFileOrDirectory(allDirName, pathTempDir);
//					//FileUtil.MoveFileOrDirectory(allDirName + ".meta", pathTempDir + ".meta");
//				}
//				else
//				{
//					UtilsLog.Error ("MoveUnResources", "just dir" + urpi.Path);
//				}
//
//			}
//
//			AssetDatabase.Refresh();

            BuildLogger.CloseBlock();
        }
Exemplo n.º 25
0
        private bool RunDirectAssembler(BuildContext context)
        {
            int         processedTopics = 0;
            bool        isSuccessful    = false;
            BuildLogger logger          = context.Logger;

            AppDomain assemblerDomain = null;

            try
            {
                assemblerDomain = AppDomain.CreateDomain(
                    "Sandcastle.BuildAssemblerDomain");

                SandcastleAssemblerTool assemblerProxy =
                    (SandcastleAssemblerTool)assemblerDomain.CreateInstanceAndUnwrap(
                        typeof(SandcastleAssemblerTool).Assembly.FullName,
                        typeof(SandcastleAssemblerTool).FullName);

                assemblerProxy.ManifestFile      = _manifestFile;
                assemblerProxy.ConfigurationFile = _configurationFile;

                isSuccessful = assemblerProxy.Run(context);

                processedTopics = assemblerProxy.TopicsProcessed;
            }
            catch (Exception ex)
            {
                logger.WriteLine(ex);
            }
            finally
            {
                if (assemblerDomain != null)
                {
                    AppDomain.Unload(assemblerDomain);
                    assemblerDomain = null;
                }
            }

            context.AddProcessedTopics(processedTopics);

            return(isSuccessful);
        }
Exemplo n.º 26
0
        public void Roslyn_SetResults_ResultsFileDoesNotExist()
        {
            // Arrange
            string rootInputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Inputs");

            WellKnownProjectProperties properties = new WellKnownProjectProperties();

            properties.SonarQubeTempPath = rootInputFolder;

            ProjectRootElement projectRoot = BuildUtilities.CreateValidProjectRoot(this.TestContext, rootInputFolder, properties);

            BuildLogger logger = new BuildLogger();

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger, TargetConstants.SetRoslynResultsTarget);

            // Assert
            logger.AssertTargetExecuted(TargetConstants.SetRoslynResultsTarget);
            BuildAssertions.AssertAnalysisSettingDoesNotExist(result, RoslynAnalysisResultsSettingName);
        }
Exemplo n.º 27
0
        public void Roslyn_Settings_NotRunForTestProject()
        {
            // Arrange
            BuildLogger logger = new BuildLogger();
            WellKnownProjectProperties properties = new WellKnownProjectProperties();

            properties.ProjectTypeGuids = TargetConstants.MsTestProjectTypeGuid; // mark the project as a test project

            ProjectRootElement projectRoot = CreateValidProjectSetup(properties);

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger, TargetConstants.OverrideRoslynAnalysisTarget);

            // Assert
            logger.AssertTargetExecuted(TargetConstants.OverrideRoslynAnalysisTarget);
            logger.AssertTargetNotExecuted(TargetConstants.SetRoslynAnalysisPropertiesTarget);
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.OverrideRoslynAnalysisTarget);

            AssertCodeAnalysisIsDisabled(result, null);
        }
Exemplo n.º 28
0
        public void Roslyn_Settings_ErrorLogAlreadySet()
        {
            // Arrange
            BuildLogger logger = new BuildLogger();
            WellKnownProjectProperties properties = new WellKnownProjectProperties();

            properties[TargetProperties.ErrorLog] = "already.set.txt";

            ProjectRootElement projectRoot = CreateValidProjectSetup(properties);

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger, TargetConstants.OverrideRoslynAnalysisTarget);

            // Assert
            logger.AssertTargetExecuted(TargetConstants.OverrideRoslynAnalysisTarget);
            logger.AssertTargetExecuted(TargetConstants.SetRoslynAnalysisPropertiesTarget);
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.OverrideRoslynAnalysisTarget);

            BuildAssertions.AssertExpectedPropertyValue(result.ProjectStateAfterBuild, TargetProperties.ErrorLog, "already.set.txt");
        }
Exemplo n.º 29
0
        protected override bool OnExecute(BuildContext context)
        {
            BuildLogger logger = context.Logger;

            //if (logger != null)
            //{
            //    logger.WriteLine("Closing the HtmlHelp Viewer...",
            //        BuildLoggerLevel.Started);
            //}

            bool closeResult = CloseIt(logger);

            //if (logger != null)
            //{
            //    logger.WriteLine("Closing the HtmlHelp Viewer.",
            //        BuildLoggerLevel.Ended);
            //}

            return(closeResult);
        }
        public void E2E_MissingProjectGuid()
        {
            // Projects with missing guids should have a warning emitted. The project info
            // should not be generated.

            // Arrange
            string rootInputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Inputs");
            string rootOutputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Outputs");

            WellKnownProjectProperties preImportProperties = CreateDefaultAnalysisProperties(rootInputFolder, rootOutputFolder);

            preImportProperties["SonarConfigPath"] = rootInputFolder;

            ProjectDescriptor descriptor = new ProjectDescriptor()
            {
                // No guid property
                IsTestProject = false,
                ParentDirectoryPath = rootInputFolder,
                ProjectFolderName = "MyProjectDir",
                ProjectFileName = "MissingProjectGuidProject.proj"
            };
            AddEmptyAnalysedCodeFile(descriptor, rootInputFolder);

            ProjectRootElement projectRoot = BuildUtilities.CreateInitializedProjectRoot(this.TestContext, descriptor, preImportProperties);

            BuildLogger logger = new BuildLogger();

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger);

            // Assert
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.DefaultBuildTarget); // Build should succeed with warnings
            ProjectInfoAssertions.AssertNoProjectInfoFilesExists(rootOutputFolder);

            logger.AssertExpectedErrorCount(0);
            logger.AssertExpectedWarningCount(1);

            BuildWarningEventArgs warning = logger.Warnings[0];
            Assert.IsTrue(warning.Message.Contains(descriptor.FullFilePath),
                "Expecting the warning to contain the full path to the bad project file");
        }
Exemplo n.º 31
0
        private void Copy(DirectoryInfo source, DirectoryInfo target,
                          BuildLogger logger)
        {
            CopyFiles(source, target, logger);

            if (!_isRecursive)
            {
                return;
            }

            DirectoryInfo[] arrSourceInfo = source.GetDirectories();

            int dirCount = (arrSourceInfo == null) ? 0 : arrSourceInfo.Length;

            for (int i = 0; i < dirCount; i++)
            {
                DirectoryInfo  sourceInfo = arrSourceInfo[i];
                FileAttributes fileAttr   = sourceInfo.Attributes;
                if (!_includeHidden)
                {
                    if ((fileAttr & FileAttributes.Hidden) == FileAttributes.Hidden)
                    {
                        continue;
                    }
                }

                DirectoryInfo targetInfo = null;
                if (_includeSecurity)
                {
                    targetInfo = target.CreateSubdirectory(sourceInfo.Name,
                                                           sourceInfo.GetAccessControl());
                }
                else
                {
                    targetInfo = target.CreateSubdirectory(sourceInfo.Name);
                }
                targetInfo.Attributes = fileAttr;

                Copy(sourceInfo, targetInfo, logger);
            }
        }
        public override void Visit(ReferenceDocument referenceDocument)
        {
            BuildExceptions.NotNull(referenceDocument, "referenceDocument");
            if (referenceDocument.DocumentType != ReferenceDocumentType.TableOfContents)
            {
                return;
            }
            if (!this.IsInitialized || _notApplicable)
            {
                return;
            }
            if (_tocExclude == null || !_tocExclude.Enabled ||
                !_tocExclude.IsActive)
            {
                return;
            }

            BuildContext context = this.Context;

            Debug.Assert(context != null);
            if (context == null)
            {
                return;
            }

            BuildLogger logger = context.Logger;

            if (logger != null)
            {
                logger.WriteLine("Begin: Excluding marked topics from the TOC.",
                                 BuildLoggerLevel.Info);
            }

            this.Visit(referenceDocument.DocumentFile, context.Logger);

            if (logger != null)
            {
                logger.WriteLine("Completed: Excluding marked topics from the TOC.",
                                 BuildLoggerLevel.Info);
            }
        }
        /// <summary>
        /// Executes the WriteProjectInfoFile target in the the supplied project.
        /// The method will check the build succeeded and that a single project
        /// output file was created.
        /// </summary>
        /// <returns>The project info file that was created during the build</returns>
        private ProjectInfo ExecuteWriteProjectInfo(ProjectRootElement projectRoot, string rootOutputFolder)
        {
            projectRoot.Save();
            BuildLogger logger = new BuildLogger();

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger, TargetConstants.CalculateSonarQubeFileListsTarget, TargetConstants.WriteProjectDataTarget);

            // Assert
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.CalculateSonarQubeFileListsTarget);
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.WriteProjectDataTarget);

            logger.AssertNoWarningsOrErrors();
            logger.AssertTargetExecuted(TargetConstants.WriteProjectDataTarget);

            // Check expected project outputs
            Assert.AreEqual(1, Directory.EnumerateDirectories(rootOutputFolder).Count(), "Only expecting one child directory to exist under the root analysis output folder");
            ProjectInfo projectInfo = ProjectInfoAssertions.AssertProjectInfoExists(rootOutputFolder, projectRoot.FullPath);

            return(projectInfo);
        }
Exemplo n.º 34
0
        public void Roslyn_Settings_NotRunForExcludedProject()
        {
            // Arrange
            BuildLogger logger = new BuildLogger();
            WellKnownProjectProperties properties = new WellKnownProjectProperties();

            properties.SonarQubeExclude            = "TRUE"; // mark the project as excluded
            properties.ResolvedCodeAnalysisRuleset = "Dummy value";

            ProjectRootElement projectRoot = CreateValidProjectSetup(properties);

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger, TargetConstants.OverrideRoslynAnalysisTarget);

            // Assert
            logger.AssertTargetExecuted(TargetConstants.OverrideRoslynAnalysisTarget);
            logger.AssertTargetNotExecuted(TargetConstants.SetRoslynAnalysisPropertiesTarget);
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.OverrideRoslynAnalysisTarget);

            AssertCodeAnalysisIsDisabled(result, properties.ResolvedCodeAnalysisRuleset);
        }
        public void StyleCop_TempFolderIsSet()
        {
            // Arrange
            string rootInputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Inputs");

            WellKnownProjectProperties properties = new WellKnownProjectProperties();

            properties.SonarQubeTempPath   = rootInputFolder;
            properties.SonarQubeOutputPath = rootInputFolder;

            ProjectRootElement projectRoot = BuildUtilities.CreateValidProjectRoot(this.TestContext, rootInputFolder, properties);

            BuildLogger logger = new BuildLogger();

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger, TargetConstants.SetStyleCopSettingsTarget);

            // Assert
            logger.AssertTargetExecuted(TargetConstants.SetStyleCopSettingsTarget);
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.SetStyleCopSettingsTarget);
        }
Exemplo n.º 36
0
        public override BuildPipelineCodes Convert(BuildResultInfo resultInfo, BuildCompression compression, string outputFolder, out BundleCRCMap output)
        {
            StartProgressBar("Archiving Resource Files", resultInfo.bundleResults.Count);
            output = new BundleCRCMap();

            foreach (var bundle in resultInfo.bundleResults)
            {
                if (!UpdateProgressBar(string.Format("Bundle: {0}", bundle.Key)))
                {
                    EndProgressBar();
                    return(BuildPipelineCodes.Canceled);
                }

                var resourceFiles = new List <ResourceFile>(bundle.Value.SelectMany(x => x.resourceFiles));

                var filePath = string.Format("{0}/{1}", outputFolder, bundle.Key);

                uint    crc;
                Hash128 hash = CalculateInputHash(resourceFiles, compression);
                if (UseCache && TryLoadFromCache(hash, outputFolder, out crc))
                {
                    output[filePath] = crc;
                    continue;
                }

                crc = BundleBuildInterface.ArchiveAndCompress(resourceFiles.ToArray(), filePath, compression);
                output[filePath] = crc;

                if (UseCache && !TrySaveToCache(hash, bundle.Key, crc, outputFolder))
                {
                    BuildLogger.LogWarning("Unable to cache ResourceFileArchiver result for bundle {0}.", bundle.Key);
                }
            }

            if (!EndProgressBar())
            {
                return(BuildPipelineCodes.Canceled);
            }
            return(BuildPipelineCodes.Success);
        }
        public void Roslyn_Settings_ValidSetup_OverrideExistingSettings_AbsolutePath()
        {
            // Arrange
            BuildLogger logger = new BuildLogger();

            // Set the ruleset property
            WellKnownProjectProperties properties = new WellKnownProjectProperties();
            properties.ResolvedCodeAnalysisRuleset = "c:\\existing.ruleset";

            // Add some existing analyzer settings
            ProjectRootElement projectRoot = CreateValidProjectSetup(properties);
            projectRoot.AddItem(TargetProperties.AnalyzerItemType, "Analyzer1.dll");
            projectRoot.AddItem(TargetProperties.AnalyzerItemType, "c:\\Analyzer2.dll");

            projectRoot.AddItem(TargetProperties.AdditionalFilesItemType, "additional1.txt");
            projectRoot.AddItem(TargetProperties.AdditionalFilesItemType, "additional2.txt");


            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger, TargetConstants.OverrideRoslynAnalysisTarget);

            // Assert
            logger.AssertTargetExecuted(TargetConstants.OverrideRoslynAnalysisTarget);
            logger.AssertTargetExecuted(TargetConstants.SetRoslynAnalysisPropertiesTarget);
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.OverrideRoslynAnalysisTarget);

            // Check the error log and ruleset properties are set
            string sourceRulesetFilePath = GetDummyRulesetFilePath();
            this.TestContext.AddResultFile(sourceRulesetFilePath);

            string targetDir = result.ProjectStateAfterBuild.GetPropertyValue(TargetProperties.TargetDir);
            string expectedErrorLog = Path.Combine(targetDir, ErrorLogFileName);

            AssertExpectedAnalysisProperties(result, expectedErrorLog, sourceRulesetFilePath, GetDummySonarLintXmlFilePath());
            BuildAssertions.AssertWarningsAreNotTreatedAsErrorsNorIgnored(result);

            // Check the analyzer properties are set as expected
            List<string> expectedAnalyzers = new List<string>(GetSonarLintAnalyzerFilePaths());
            AssertExpectedItemValuesExists(result, TargetProperties.AnalyzerItemType, expectedAnalyzers.ToArray());
        }
Exemplo n.º 38
0
        public void E2E_FxCop_OutputFolderSet_SonarRulesetNotFound()
        {
            // Arrange
            string rootInputFolder  = TestUtils.CreateTestSpecificFolder(this.TestContext, "Inputs");
            string rootOutputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Outputs");

            // Set the output folder and config path
            // Don't create a ruleset file on disc
            string fxCopLogFile = Path.Combine(rootInputFolder, "FxCopResults.xml");
            WellKnownProjectProperties preImportProperties = new WellKnownProjectProperties();

            preImportProperties.SonarQubeTempPath   = rootOutputFolder; // FIXME
            preImportProperties.SonarQubeOutputPath = rootOutputFolder;
            preImportProperties.RunCodeAnalysis     = "true";           // our targets should override this value
            preImportProperties.CodeAnalysisLogFile = fxCopLogFile;
            preImportProperties.SonarQubeConfigPath = rootInputFolder;
            ProjectRootElement projectRoot = BuildUtilities.CreateValidProjectRoot(this.TestContext, rootInputFolder, preImportProperties);

            BuildLogger logger = new BuildLogger();

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger);

            // Assert
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.DefaultBuildTarget);

            logger.AssertTargetExecuted(TargetConstants.OverrideFxCopSettingsTarget);  // output folder is set so this should be executed
            logger.AssertTargetNotExecuted(TargetConstants.SetFxCopResultsTarget);

            // We expect the core FxCop *target* to have been started, but it should then be skipped
            // executing the FxCop *task* because the condition on the target is false
            // -> the FxCop output file should not be produced
            AssertFxCopNotExecuted(logger);

            Assert.IsFalse(File.Exists(fxCopLogFile), "FxCop log file should not have been produced");

            ProjectInfo projectInfo = ProjectInfoAssertions.AssertProjectInfoExists(rootOutputFolder, projectRoot.FullPath);

            ProjectInfoAssertions.AssertAnalysisResultDoesNotExists(projectInfo, AnalysisType.FxCop.ToString());
        }
        public void Roslyn_TargetExecutionOrder()
        {
            // Arrange
            string rootInputFolder  = TestUtils.CreateTestSpecificFolder(this.TestContext, "Inputs");
            string rootOutputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Outputs");

            WellKnownProjectProperties properties = new WellKnownProjectProperties
            {
                SonarQubeTempPath   = rootInputFolder,
                SonarQubeOutputPath = rootInputFolder,
                SonarQubeConfigPath = rootOutputFolder
            };

            ProjectRootElement projectRoot = BuildUtilities.CreateValidProjectRoot(this.TestContext, rootInputFolder, properties);


            // Add some settings we expect to be ignored
            AddAnalysisSetting("sonar.other.setting", "other value", projectRoot);
            projectRoot.Save();

            BuildLogger logger = new BuildLogger();

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger, TargetConstants.DefaultBuildTarget);

            // Assert
            // Checks that should succeed irrespective of the MSBuild version
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.DefaultBuildTarget);
            logger.AssertTargetExecuted(TargetConstants.OverrideRoslynAnalysisTarget);

            logger.AssertExpectedTargetOrdering(
                TargetConstants.ResolveCodeAnalysisRuleSet,
                TargetConstants.CategoriseProjectTarget,
                TargetConstants.OverrideRoslynAnalysisTarget,
                TargetConstants.SetRoslynAnalysisPropertiesTarget,
                TargetConstants.CoreCompile,
                TargetConstants.DefaultBuildTarget,
                TargetConstants.SetRoslynResultsTarget,
                TargetConstants.WriteProjectDataTarget);
        }
Exemplo n.º 40
0
        private void ApplyAttributesVisibility(
            XPathNavigator rootNavigator, BuildLogger logger)
        {
            if (_visibility.AttributeInformation)
            {
                return;
            }

            XPathNodeIterator iterator = rootNavigator.Select("api/attributes/attribute");

            if (iterator == null || iterator.Count == 0)
            {
                return;
            }

            XPathNavigator[] navigators = ToClonedArray(iterator);

            int itemCount = 0;

            foreach (XPathNavigator navigator in navigators)
            {
                XPathNavigator typeNavigator = navigator.SelectSingleNode("type");

                if (typeNavigator != null)
                {
                    string attributeApi = typeNavigator.GetAttribute("api", String.Empty);
                    if (typeNavigator != null && !_visibility.IsAttributeKept(attributeApi))
                    {
                        navigator.DeleteSelf();
                        itemCount++;
                    }
                }
            }

            if (itemCount > 0 && logger != null)
            {
                logger.WriteLine(itemCount.ToString().PadRight(5) +
                                 " Attributes removed.", BuildLoggerLevel.Info);
            }
        }
Exemplo n.º 41
0
        static internal void GatherAssetRepresentations(string assetPath, System.Func <string, UnityEngine.Object[]> loadAllAssetRepresentations, ObjectIdentifier[] includedObjects, out ExtendedAssetData extendedData)
        {
            extendedData = null;
            var representations = loadAllAssetRepresentations(assetPath);

            if (representations.IsNullOrEmpty())
            {
                return;
            }

            var resultData = new ExtendedAssetData();

            for (int j = 0; j < representations.Length; j++)
            {
                if (representations[j] == null)
                {
                    BuildLogger.LogWarning($"SubAsset {j} inside {assetPath} is null. It will not be included in the build.");
                    continue;
                }

                if (AssetDatabase.IsMainAsset(representations[j]))
                {
                    continue;
                }

                string guid;
                long   localId;
                if (!AssetDatabase.TryGetGUIDAndLocalFileIdentifier(representations[j], out guid, out localId))
                {
                    continue;
                }

                resultData.Representations.AddRange(includedObjects.Where(x => x.localIdentifierInFile == localId));
            }

            if (resultData.Representations.Count > 0)
            {
                extendedData = resultData;
            }
        }
Exemplo n.º 42
0
        private void BuildAssetBundles()
        {
            if (!BuildPathValidator.ValidOutputFolder(m_Settings.outputPath, true))
            {
                EditorUtility.DisplayDialog("Invalid Output Folder", string.Format(BuildPathValidator.kPathNotValidError, m_Settings.outputPath), "Ok");
                return;
            }

            if (!EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
            {
                return;
            }

            if (m_Settings.useExperimentalPipeline)
            {
                ExperimentalBuildPipeline();
                return;
            }

            var buildTimer = new Stopwatch();

            buildTimer.Start();

            var exitCode = LegacyBuildPipeline();

            buildTimer.Stop();
            if (exitCode == BuildPipelineCodes.Success)
            {
                BuildLogger.Log("Build Asset Bundles successful in: {0:c}", buildTimer.Elapsed);
            }
            else if (exitCode == BuildPipelineCodes.Canceled)
            {
                BuildLogger.LogWarning("Build Asset Bundles canceled in: {0:c}", buildTimer.Elapsed);
            }
            else
            {
                BuildLogger.LogError("Build Asset Bundles failed in: {0:c}. Error: {1}.", buildTimer.Elapsed, exitCode);
            }
        }
Exemplo n.º 43
0
        private void StartHelpAgent(BuildContext context)
        {
            if (ProcessRunner.IsProcessOpen("HelpLibAgent"))
            {
                return;
            }

            BuildLogger logger = context.Logger;

            if (logger != null)
            {
                logger.WriteLine("Starting: Microsoft Help Library Agent",
                                 BuildLoggerLevel.Info);
            }

            using (Process proc = new Process())
            {
                proc.EnableRaisingEvents = false;
                proc.StartInfo.FileName  = GetAgentLocation();
                proc.Start();
            }
        }
Exemplo n.º 44
0
        public void Roslyn_Settings_TempFolderIsNotSet()
        {
            // Arrange
            BuildLogger logger = new BuildLogger();

            WellKnownProjectProperties properties = new WellKnownProjectProperties();

            properties.ErrorLog = "pre-existing.log";
            properties.ResolvedCodeAnalysisRuleset = "pre-existing.ruleset";

            ProjectRootElement projectRoot = CreateValidProjectSetup(properties);

            projectRoot.AddProperty(TargetProperties.SonarQubeTempPath, string.Empty); // needs to overwritten once the valid project has been created

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger, TargetConstants.OverrideRoslynAnalysisTarget);

            // Assert
            logger.AssertTargetNotExecuted(TargetConstants.OverrideRoslynAnalysisTarget);
            logger.AssertTargetNotExecuted(TargetConstants.SetRoslynAnalysisPropertiesTarget);
            AssertExpectedAnalysisProperties(result, "pre-existing.log", "pre-existing.ruleset"); // existing properties should not be changed
        }
        static HuaweiSDKSettings CreateSettings()
        {
            const string funcBlock = "HuaweiSDKEditor.CreateSettings()";

            BuildLogger.OpenBlock(funcBlock);

            string curDir = GetCurDir();

            if (Directory.Exists(curDir) == false)
            {
                return(null);
            }
            HuaweiSDKSettings settings = UtilsAsset.CreateAsset <HuaweiSDKSettings> (curDir);

            if (settings != null)
            {
                // 初始化
                settings.Init();
            }
            BuildLogger.CloseBlock();
            return(settings);
        }
        public void Roslyn_Settings_SettingsMissing_NoError()
        {
            // Arrange
            BuildLogger logger = new BuildLogger();

            // Set the config directory so the targets know where to look for the analysis config file
            string confDir = TestUtils.CreateTestSpecificFolder(this.TestContext, "config");

            // Create a valid config file that does not contain analyzer settings
            AnalysisConfig config         = new AnalysisConfig();
            string         configFilePath = Path.Combine(confDir, FileConstants.ConfigFileName);

            config.Save(configFilePath);

            // Create the project
            WellKnownProjectProperties properties = new WellKnownProjectProperties();

            properties.SonarQubeConfigPath         = confDir;
            properties.ResolvedCodeAnalysisRuleset = "c:\\should.be.overridden.ruleset";

            ProjectRootElement projectRoot = CreateValidProjectSetup(properties);

            projectRoot.AddItem(TargetProperties.AnalyzerItemType, "should.be.removed.analyzer1.dll");
            projectRoot.AddItem(TargetProperties.AdditionalFilesItemType, "should.be.removed.additional1.txt");

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger, TargetConstants.OverrideRoslynAnalysisTarget);

            // Assert
            logger.AssertTargetExecuted(TargetConstants.OverrideRoslynAnalysisTarget);
            logger.AssertTargetExecuted(TargetConstants.SetRoslynAnalysisPropertiesTarget);
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.OverrideRoslynAnalysisTarget);

            // Check the error log and ruleset properties are set
            AssertErrorLogIsSetBySonarQubeTargets(result);
            AssertExpectedResolvedRuleset(result, string.Empty);
            BuildAssertions.AssertExpectedItemGroupCount(result, TargetProperties.AnalyzerItemType, 0);
            BuildAssertions.AssertExpectedItemGroupCount(result, TargetProperties.AdditionalFilesItemType, 0);
        }
        public void Roslyn_SetResults_ResultsFileExists()
        {
            // Arrange
            string rootInputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Inputs");

            string resultsFile = TestUtils.CreateTextFile(rootInputFolder, "error.report.txt", "dummy report content");

            WellKnownProjectProperties properties = new WellKnownProjectProperties();
            properties.SonarQubeTempPath = rootInputFolder;
            properties[TargetProperties.ErrorLog] = resultsFile;

            ProjectRootElement projectRoot = BuildUtilities.CreateValidProjectRoot(this.TestContext, rootInputFolder, properties);

            BuildLogger logger = new BuildLogger();

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger, TargetConstants.SetRoslynResultsTarget);

            // Assert
            logger.AssertTargetExecuted(TargetConstants.SetRoslynResultsTarget);
            BuildAssertions.AssertExpectedAnalysisSetting(result, RoslynAnalysisResultsSettingName, resultsFile);
        }
        public void Roslyn_Settings_SettingsMissing_NoError()
        {
            // Arrange
            BuildLogger logger = new BuildLogger();

            // Set the config directory so the targets know where to look for the analysis config file
            string confDir = TestUtils.CreateTestSpecificFolder(this.TestContext, "config");

            // Create a valid config file that does not contain analyzer settings
            AnalysisConfig config = new AnalysisConfig();
            string configFilePath = Path.Combine(confDir, FileConstants.ConfigFileName);
            config.Save(configFilePath);

            // Create the project
            WellKnownProjectProperties properties = new WellKnownProjectProperties();
            properties.SonarQubeConfigPath = confDir;
            properties.ResolvedCodeAnalysisRuleset = "c:\\should.be.overridden.ruleset";

            ProjectRootElement projectRoot = CreateValidProjectSetup(properties);

            projectRoot.AddItem(TargetProperties.AnalyzerItemType, "should.be.removed.analyzer1.dll");
            projectRoot.AddItem(TargetProperties.AdditionalFilesItemType, "should.be.removed.additional1.txt");

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger, TargetConstants.OverrideRoslynAnalysisTarget);

            // Assert
            logger.AssertTargetExecuted(TargetConstants.OverrideRoslynAnalysisTarget);
            logger.AssertTargetExecuted(TargetConstants.SetRoslynAnalysisPropertiesTarget);
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.OverrideRoslynAnalysisTarget);

            // Check the error log and ruleset properties are set
            AssertErrorLogIsSetBySonarQubeTargets(result);
            AssertExpectedResolvedRuleset(result, string.Empty);
            BuildAssertions.AssertExpectedItemGroupCount(result, TargetProperties.AnalyzerItemType, 0);
            BuildAssertions.AssertExpectedItemGroupCount(result, TargetProperties.AdditionalFilesItemType, 0);
        }
        public void Roslyn_Settings_ErrorLogAlreadySet()
        {
            // Arrange
            BuildLogger logger = new BuildLogger();
            WellKnownProjectProperties properties = new WellKnownProjectProperties();
            properties[TargetProperties.ErrorLog] = "already.set.txt";

            ProjectRootElement projectRoot = CreateValidProjectSetup(properties);

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger, TargetConstants.OverrideRoslynAnalysisTarget);

            // Assert
            logger.AssertTargetExecuted(TargetConstants.OverrideRoslynAnalysisTarget);
            logger.AssertTargetExecuted(TargetConstants.SetRoslynAnalysisPropertiesTarget);
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.OverrideRoslynAnalysisTarget);

            // Check the intermediate working properties have the expected values
            BuildAssertions.AssertExpectedPropertyValue(result.ProjectStateAfterBuild, "SonarQubeRoslynRulesetExists", "True");
            BuildAssertions.AssertExpectedPropertyValue(result.ProjectStateAfterBuild, "SonarQubeRoslynAssemblyExists", "True");
            BuildAssertions.AssertExpectedPropertyValue(result.ProjectStateAfterBuild, "SonarLintFound", "true");

            BuildAssertions.AssertExpectedPropertyValue(result.ProjectStateAfterBuild, TargetProperties.ErrorLog, "already.set.txt");
        }
 private void AssertFxCopNotExecuted(BuildLogger logger)
 {
     // FxCop has a "RunCodeAnalysis" target and a "CodeAnalysis" task: the target executes the task.
     // We are interested in whether the task is executed or not as that is what will actually produce
     // the output file (it's possible that the target will be executed, but that it will decide
     // to skip the task because the required conditions are not met).
     logger.AssertTaskNotExecuted(TargetConstants.FxCopTask);
 }
        public void ImportsBefore_TargetsExist()
        {
            // 1. Pre-build
            // Arrange
            string dummySonarTargetsDir = this.EnsureDummyIntegrationTargetsFileExists();

            WellKnownProjectProperties preImportProperties = new WellKnownProjectProperties();
            preImportProperties.SonarQubeTempPath = Path.GetTempPath();
            preImportProperties.SonarQubeTargetsPath = Path.GetDirectoryName(dummySonarTargetsDir);
            preImportProperties.TeamBuild2105BuildDirectory = "";
            preImportProperties.TeamBuildLegacyBuildDirectory = "";

            // Act
            ProjectInstance projectInstance = this.CreateAndEvaluateProject(preImportProperties);

            // Assert
            BuildAssertions.AssertExpectedPropertyValue(projectInstance, TargetProperties.SonarQubeTargetFilePath, dummySonarTargetsDir);
            AssertAnalysisTargetsAreImported(projectInstance);


            // 2. Now build -> succeeds
            BuildLogger logger = new BuildLogger();

            BuildResult result = BuildUtilities.BuildTargets(projectInstance, logger);

            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.DefaultBuildTarget);
            logger.AssertTargetExecuted(TargetConstants.ImportBeforeInfoTarget);
            logger.AssertExpectedErrorCount(0);
        }
        public void Roslyn_Settings_ValidSetup_MergeWithExistingSettings()
        {
            // Arrange
            BuildLogger logger = new BuildLogger();

            // Set the ruleset property
            WellKnownProjectProperties properties = new WellKnownProjectProperties();
            properties.ResolvedCodeAnalysisRuleset = "c:\\existing.ruleset";

            // Add some existing analyzer settings
            ProjectRootElement projectRoot = CreateValidProjectSetup(properties);
            projectRoot.AddItem(TargetProperties.AnalyzerItemType, "Analyzer1.dll");
            projectRoot.AddItem(TargetProperties.AnalyzerItemType, "c:\\Analyzer2.dll");

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger, TargetConstants.OverrideRoslynAnalysisTarget);

            // Assert
            logger.AssertTargetExecuted(TargetConstants.OverrideRoslynAnalysisTarget);
            logger.AssertTargetExecuted(TargetConstants.SetRoslynAnalysisPropertiesTarget);
            logger.AssertTaskExecuted(TargetConstants.MergeResultSetsTask);
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.OverrideRoslynAnalysisTarget);

            // Check the error log and ruleset properties are set
            string finalRulesetFilePath = GetDummyRulesetFilePath();
            this.TestContext.AddResultFile(finalRulesetFilePath);

            string targetDir = result.ProjectStateAfterBuild.GetPropertyValue(TargetProperties.TargetDir);
            string expectedErrorLog = Path.Combine(targetDir, ErrorLogFileName);
            AssertExpectedAnalysisProperties(result, expectedErrorLog, finalRulesetFilePath);

            RuleSetAssertions.AssertExpectedIncludeFiles(finalRulesetFilePath, "c:\\existing.ruleset");
            RuleSetAssertions.AssertExpectedIncludeAction(finalRulesetFilePath, "c:\\existing.ruleset", RuleSetAssertions.DefaultActionValue);
        }
        public void Roslyn_TargetExecutionOrder()
        {
            // Arrange
            string rootInputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Inputs");
            string rootOutputFolder = TestUtils.CreateTestSpecificFolder(this.TestContext, "Outputs");

            WellKnownProjectProperties properties = new WellKnownProjectProperties();
            properties.SonarQubeTempPath = rootInputFolder;
            properties.SonarQubeOutputPath = rootInputFolder;
            properties.SonarQubeConfigPath = rootOutputFolder;

            ProjectRootElement projectRoot = BuildUtilities.CreateValidProjectRoot(this.TestContext, rootInputFolder, properties);

            // Add some settings we expect to be ignored
            AddAnalysisSetting("sonar.other.setting", "other value", projectRoot);
            projectRoot.Save();

            BuildLogger logger = new BuildLogger();

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger, TargetConstants.DefaultBuildTarget);

            // Assert
            // Checks that should succeed irrespective of the MSBuild version
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.DefaultBuildTarget);
            logger.AssertTargetExecuted(TargetConstants.OverrideRoslynAnalysisTarget);

            // Note: use VS2013 to run this test using MSBuild 12.0.
            // Use VS2015 to run this test using MSBuild 14.0.
            if (result.ProjectStateAfterBuild.ToolsVersion.CompareTo("14.0") < 0)
            {
                logger.AssertTargetNotExecuted(TargetConstants.ResolveCodeAnalysisRuleSet); // sanity-check: should only be in MSBuild 14.0+
                Assert.Inconclusive("This test requires MSBuild 14.0 to be installed. Version used: {0}", result.ProjectStateAfterBuild.ToolsVersion);
            }
            else
            {
                // MSBuild 14.0+ checks
                logger.AssertExpectedTargetOrdering(
                    TargetConstants.ResolveCodeAnalysisRuleSet,
                    TargetConstants.CategoriseProjectTarget,
                    TargetConstants.OverrideRoslynAnalysisTarget,
                    TargetConstants.SetRoslynAnalysisPropertiesTarget,
                    TargetConstants.CoreCompile,
                    TargetConstants.DefaultBuildTarget,
                    TargetConstants.SetRoslynResultsTarget,
                    TargetConstants.WriteProjectDataTarget);
            }
        }
        public void Roslyn_Settings_TempFolderIsNotSet()
        {
            // Arrange
            BuildLogger logger = new BuildLogger();

            WellKnownProjectProperties properties = new WellKnownProjectProperties();
            properties.ErrorLog = "pre-existing.log";
            properties.ResolvedCodeAnalysisRuleset = "pre-existing.ruleset";

            ProjectRootElement projectRoot = CreateValidProjectSetup(properties);
            projectRoot.AddProperty(TargetProperties.SonarQubeTempPath, string.Empty); // needs to overwritten once the valid project has been created

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger, TargetConstants.OverrideRoslynAnalysisTarget);

            // Assert
            logger.AssertTargetNotExecuted(TargetConstants.OverrideRoslynAnalysisTarget);
            logger.AssertTargetNotExecuted(TargetConstants.SetRoslynAnalysisPropertiesTarget);
            AssertExpectedAnalysisProperties(result, "pre-existing.log", "pre-existing.ruleset"); // existing properties should not be changed
        }
        public void Roslyn_Settings_ValidSetup()
        {
            // Arrange
            BuildLogger logger = new BuildLogger();
            ProjectRootElement projectRoot = CreateValidProjectSetup(null);

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger, TargetConstants.OverrideRoslynAnalysisTarget);

            // Assert
            logger.AssertTargetExecuted(TargetConstants.OverrideRoslynAnalysisTarget);
            logger.AssertTargetExecuted(TargetConstants.SetRoslynAnalysisPropertiesTarget);
            logger.AssertTaskNotExecuted(TargetConstants.MergeResultSetsTask);
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.OverrideRoslynAnalysisTarget);

            // Check the intermediate working properties have the expected values
            BuildAssertions.AssertExpectedPropertyValue(result.ProjectStateAfterBuild, "SonarQubeRoslynRulesetExists", "True");
            BuildAssertions.AssertExpectedPropertyValue(result.ProjectStateAfterBuild, "SonarQubeRoslynAssemblyExists", "True");
            BuildAssertions.AssertExpectedPropertyValue(result.ProjectStateAfterBuild, "SonarLintFound", "true");

            // Check the error log and ruleset properties are set
            string targetDir = result.ProjectStateAfterBuild.GetPropertyValue(TargetProperties.TargetDir);
            string expectedErrorLog = Path.Combine(targetDir, ErrorLogFileName);
            AssertExpectedAnalysisProperties(result, expectedErrorLog, GetDummyRulesetFilePath());
            AssertExpectedAnalyzersExists(result, GetSonarLintAnalyzerFilePaths());
        }
        public void Roslyn_Settings_RuleSetDoesNotExist()
        {
            // Arrange
            BuildLogger logger = new BuildLogger();
            WellKnownProjectProperties properties = new WellKnownProjectProperties();
            properties.ResolvedCodeAnalysisRuleset = "pre-existing.ruleset";
            properties.ErrorLog = "pre-existing.log";

            ProjectRootElement projectRoot = CreateValidProjectSetup(properties);
            this.DeleteDummyRulesetFile();

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger, TargetConstants.OverrideRoslynAnalysisTarget);

            // Assert
            logger.AssertTargetExecuted(TargetConstants.OverrideRoslynAnalysisTarget);
            logger.AssertTargetExecuted(TargetConstants.SetRoslynAnalysisPropertiesTarget);
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.OverrideRoslynAnalysisTarget);

            // Check the intermediate working properties have the expected values
            BuildAssertions.AssertExpectedPropertyValue(result.ProjectStateAfterBuild, "SonarQubeRoslynRulesetExists", "False");
            BuildAssertions.AssertExpectedPropertyValue(result.ProjectStateAfterBuild, "SonarQubeRoslynAssemblyExists", "True");
            BuildAssertions.AssertExpectedPropertyValue(result.ProjectStateAfterBuild, "SonarLintFound", "false");

            AssertExpectedAnalysisProperties(result, "pre-existing.log", "pre-existing.ruleset");
        }
        public void Roslyn_Settings_NotRunForTestProject()
        {
            // Arrange
            BuildLogger logger = new BuildLogger();
            WellKnownProjectProperties properties = new WellKnownProjectProperties();
            properties.ProjectTypeGuids = TargetConstants.MsTestProjectTypeGuid; // mark the project as a test project

            ProjectRootElement projectRoot = CreateValidProjectSetup(properties);

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger, TargetConstants.OverrideRoslynAnalysisTarget);

            // Assert
            logger.AssertTargetExecuted(TargetConstants.OverrideRoslynAnalysisTarget);
            logger.AssertTargetNotExecuted(TargetConstants.SetRoslynAnalysisPropertiesTarget);
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.OverrideRoslynAnalysisTarget);

            AssertCodeAnalysisIsDisabled(result);
        }
        public void ImportsBefore_MissingAnalysisTargets()
        {
            // 1. Prebuild
            // Arrange
            WellKnownProjectProperties preImportProperties = new WellKnownProjectProperties();
            preImportProperties.SonarQubeTempPath = "nonExistentPath";
            preImportProperties.MSBuildExtensionsPath = "nonExistentPath";
            preImportProperties.TeamBuild2105BuildDirectory = "";
            preImportProperties.TeamBuildLegacyBuildDirectory = "";

            // Act
            ProjectInstance projectInstance = this.CreateAndEvaluateProject(preImportProperties);

            // Assert
            BuildAssertions.AssertExpectedPropertyValue(projectInstance, TargetProperties.SonarQubeTargetsPath, @"nonExistentPath\bin\targets");
            BuildAssertions.AssertExpectedPropertyValue(projectInstance, TargetProperties.SonarQubeTargetFilePath, @"nonExistentPath\bin\targets\SonarQube.Integration.targets");

            AssertAnalysisTargetsAreNotImported(projectInstance); // Targets should not be imported


            // 2. Now build -> fails with an error message
            BuildLogger logger = new BuildLogger();

            BuildResult result = BuildUtilities.BuildTargets(projectInstance, logger);

            BuildAssertions.AssertTargetFailed(result, TargetConstants.DefaultBuildTarget);
            logger.AssertTargetExecuted(TargetConstants.ImportBeforeInfoTarget);
            logger.AssertExpectedErrorCount(1);

            string projectName = Path.GetFileName(projectInstance.FullPath);
            Assert.IsTrue(logger.Errors[0].Message.Contains(projectName), "Expecting the error message to contain the project file name");
        }
        public void Roslyn_Settings_Analyzer_AssemblyExists()
        {
            // Arrange
            BuildLogger logger = new BuildLogger();
            WellKnownProjectProperties properties = new WellKnownProjectProperties();

            ProjectRootElement projectRoot = CreateValidProjectSetup(properties);

            projectRoot.AddItem(TargetProperties.AnalyzerItemType, "analyzer1.dll"); // additional -> preserve
            projectRoot.AddItem(TargetProperties.AnalyzerItemType, "c:\\myfolder\\analyzer2.dll"); // additional -> preserve
            projectRoot.AddItem(TargetProperties.AnalyzerItemType, "sonarlint.dll"); // relative path -> remove
            projectRoot.AddItem(TargetProperties.AnalyzerItemType, "c:\\myfolder\\sonarlint.dll"); // absolute path -> remove
            projectRoot.AddItem(TargetProperties.AnalyzerItemType, "XXSONARLINT.dll"); // case-sensitivity -> remove
            projectRoot.AddItem(TargetProperties.AnalyzerItemType, "sonarLint.dll.xxx"); // doesn't match -> preserve
            projectRoot.AddItem(TargetProperties.AnalyzerItemType, "c:\\sonarLint\\my.dll"); // doesn't match -> preserve

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger, TargetConstants.OverrideRoslynAnalysisTarget);

            // Assert
            logger.AssertTargetExecuted(TargetConstants.OverrideRoslynAnalysisTarget);
            logger.AssertTargetExecuted(TargetConstants.SetRoslynAnalysisPropertiesTarget);
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.OverrideRoslynAnalysisTarget);

            // Check the intermediate working properties have the expected values
            BuildAssertions.AssertExpectedPropertyValue(result.ProjectStateAfterBuild, "SonarQubeRoslynRulesetExists", "True");
            BuildAssertions.AssertExpectedPropertyValue(result.ProjectStateAfterBuild, "SonarLintFound", "true");

            // Check the analyzer properties are set as expected
            List<string> expectedAnalyzers = new List<string>(GetSonarLintAnalyzerFilePaths());
            expectedAnalyzers.Add("analyzer1.dll");
            expectedAnalyzers.Add("c:\\myfolder\\analyzer2.dll");
            expectedAnalyzers.Add("sonarLint.dll.xxx");
            expectedAnalyzers.Add("c:\\sonarLint\\my.dll");

            AssertExpectedAnalyzersExists(result, expectedAnalyzers.ToArray());
        }
        public void Roslyn_Settings_Analyzer_AssemblyDoesNotExist()
        {
            // Arrange
            BuildLogger logger = new BuildLogger();
            ProjectRootElement projectRoot = CreateValidProjectSetup(null);

            this.DeleteDummySonarLintFiles();

            // The downloaded SonarLint.dll could not be found so any existing settings should be preserved
            projectRoot.AddItem(TargetProperties.AnalyzerItemType, "analyzer1.dll");
            projectRoot.AddItem(TargetProperties.AnalyzerItemType, "c:\\myfolder\\analyzer2.dll");
            projectRoot.AddItem(TargetProperties.AnalyzerItemType, "c:\\myfolder\\sonarlint.dll");

            // Act
            BuildResult result = BuildUtilities.BuildTargets(projectRoot, logger, TargetConstants.OverrideRoslynAnalysisTarget);

            // Assert
            logger.AssertTargetExecuted(TargetConstants.OverrideRoslynAnalysisTarget);
            logger.AssertTargetExecuted(TargetConstants.SetRoslynAnalysisPropertiesTarget);
            BuildAssertions.AssertTargetSucceeded(result, TargetConstants.OverrideRoslynAnalysisTarget);

            // Check the intermediate working properties have the expected values
            BuildAssertions.AssertExpectedPropertyValue(result.ProjectStateAfterBuild, "SonarQubeRoslynRulesetExists", "True");
            BuildAssertions.AssertExpectedPropertyValue(result.ProjectStateAfterBuild, "SonarLintFound", "false");

            // Check the analyzer properties are set as expected
            AssertExpectedAnalyzersExists(result,
                "analyzer1.dll",
                "c:\\myfolder\\analyzer2.dll",
                "c:\\myfolder\\sonarlint.dll");
        }