コード例 #1
0
ファイル: ScriptTest.cs プロジェクト: JeremySkinner/Phantom
        public void BaseSetup()
        {
            Writer = new StringWriter();
            Console.SetOut(Writer);

            if (Runner == null) {
                var container = new CompositionContainer(new DirectoryCatalog(Directory.GetCurrentDirectory()));
                Runner = container.GetExportedValue<BuildRunner>();
            }

            Options = new PhantomOptions();

            Setup();
        }
コード例 #2
0
        public void Roslyn_Settings_ValidSetup_NonLegacyServer_MergeSettings()
        {
            // Arrange

            var dir = TestUtils.CreateTestSpecificFolderWithSubPaths(TestContext);
            var dummyQpRulesetPath = TestUtils.CreateValidEmptyRuleset(dir, "dummyQp");

            // Create a valid config containing analyzer settings
            var config = new AnalysisConfig
            {
                SonarQubeVersion = "7.5", // non-legacy version
                ServerSettings   = new AnalysisProperties
                {
                    new Property {
                        Id = "sonar.cs.roslyn.ignoreIssues", Value = "false"
                    }
                },
                AnalyzersSettings = new List <AnalyzerSettings>
                {
                    new AnalyzerSettings
                    {
                        Language        = "cs",
                        RuleSetFilePath = dummyQpRulesetPath,
                        AnalyzerPlugins = new List <AnalyzerPlugin>
                        {
                            CreateAnalyzerPlugin("c:\\data\\new\\analyzer1.dll", "c:\\new.analyzer2.dll")
                        },
                        AdditionalFilePaths = new List <string> {
                            "c:\\config\\duplicate.1.txt", "c:\\duplicate.2.txt"
                        }
                    }
                }
            };

            var testSpecificProjectXml = @"
  <PropertyGroup>
    <ResolvedCodeAnalysisRuleSet>c:\original.ruleset</ResolvedCodeAnalysisRuleSet>
    <Language>C#</Language>
  </PropertyGroup>

  <ItemGroup>
    <!-- all analyzers specified in the project file should be preserved -->
    <Analyzer Include='c:\original\should.be.removed\analyzer1.dll' />
    <Analyzer Include='original\should.be.preserved\analyzer3.dll' />
  </ItemGroup>
  <ItemGroup>
    <!-- These additional files don't match ones in the config and should be preserved -->
    <AdditionalFiles Include='should.not.be.removed.additional1.txt' />
    <AdditionalFiles Include='should.not.be.removed.additional2.txt' />

    <!-- This additional file matches one in the config and should be replaced -->
    <AdditionalFiles Include='d:/should.be.removed/DUPLICATE.1.TXT' />
    <AdditionalFiles Include='d:\should.be.removed\duplicate.2.TXT' />

  </ItemGroup>
";
            var projectFilePath        = CreateProjectFile(config, testSpecificProjectXml);

            // Act
            var result = BuildRunner.BuildTargets(TestContext, projectFilePath, TargetConstants.OverrideRoslynAnalysisTarget);

            // Assert
            result.AssertTargetExecuted(TargetConstants.CreateProjectSpecificDirs);
            result.AssertTargetExecuted(TargetConstants.OverrideRoslynAnalysisTarget);
            result.AssertTargetExecuted(TargetConstants.SetRoslynAnalysisPropertiesTarget);
            result.BuildSucceeded.Should().BeTrue();

            // Check the error log and ruleset properties are set
            AssertErrorLogIsSetBySonarQubeTargets(result);

            var actualProjectSpecificConfFolder = result.GetCapturedPropertyValue(TargetProperties.ProjectSpecificConfDir);

            Directory.Exists(actualProjectSpecificConfFolder).Should().BeTrue();

            var expectedMergedRuleSetFilePath = Path.Combine(actualProjectSpecificConfFolder, "merged.ruleset");

            AssertExpectedResolvedRuleset(result, expectedMergedRuleSetFilePath);
            RuleSetAssertions.CheckMergedRulesetFile(actualProjectSpecificConfFolder,
                                                     @"c:\original.ruleset");

            AssertExpectedAdditionalFiles(result,
                                          result.GetCapturedPropertyValue(TargetProperties.ProjectConfFilePath),
                                          "should.not.be.removed.additional1.txt",
                                          "should.not.be.removed.additional2.txt",
                                          "c:\\config\\duplicate.1.txt",
                                          "c:\\duplicate.2.txt");

            AssertExpectedAnalyzers(result,
                                    "c:\\data\\new\\analyzer1.dll",
                                    "c:\\new.analyzer2.dll",
                                    "original\\should.be.preserved\\analyzer3.dll");

            AssertWarningsAreNotTreatedAsErrorsNorIgnored(result);
        }
コード例 #3
0
        public void Roslyn_Settings_ValidSetup_LegacyServer_Override_Analyzers()
        {
            // Arrange

            // Create a valid config containing analyzer settings
            var config = new AnalysisConfig
            {
                SonarQubeHostUrl  = "http://sonarqube.com",
                SonarQubeVersion  = "6.7", // legacy version
                AnalyzersSettings = new List <AnalyzerSettings>
                {
                    new AnalyzerSettings
                    {
                        Language        = "cs",
                        RuleSetFilePath = "d:\\my.ruleset",
                        AnalyzerPlugins = new List <AnalyzerPlugin>
                        {
                            CreateAnalyzerPlugin("c:\\data\\new.analyzer1.dll"),
                            CreateAnalyzerPlugin("c:\\new.analyzer2.dll")
                        },
                        AdditionalFilePaths = new List <string> {
                            "c:\\config.1.txt", "c:\\config.2.txt"
                        }
                    }
                }
            };

            var testSpecificProjectXml = @"
  <PropertyGroup>
    <ResolvedCodeAnalysisRuleSet>c:\should.be.overridden.ruleset</ResolvedCodeAnalysisRuleSet>
    <Language>C#</Language>
  </PropertyGroup>

  <ItemGroup>
    <!-- all analyzers specified in the project file should be removed -->
    <Analyzer Include='c:\should.be.removed.analyzer2.dll' />
    <Analyzer Include='should.be.removed.analyzer1.dll' />
  </ItemGroup>
  <ItemGroup>
    <!-- These additional files don't match ones in the config and should be preserved -->
    <AdditionalFiles Include='should.not.be.removed.additional1.txt' />
    <AdditionalFiles Include='should.not.be.removed.additional2.txt' />

    <!-- This additional file matches one in the config and should be replaced -->
    <AdditionalFiles Include='should.be.removed/CONFIG.1.TXT' />
    <AdditionalFiles Include='should.be.removed\CONFIG.2.TXT' />

  </ItemGroup>
";
            var projectFilePath        = CreateProjectFile(config, testSpecificProjectXml);

            // Act
            var result = BuildRunner.BuildTargets(TestContext, projectFilePath, TargetConstants.OverrideRoslynAnalysisTarget);

            // Assert
            result.AssertTargetExecuted(TargetConstants.CreateProjectSpecificDirs);
            result.AssertTargetExecuted(TargetConstants.OverrideRoslynAnalysisTarget);
            result.AssertTargetExecuted(TargetConstants.SetRoslynAnalysisPropertiesTarget);
            result.BuildSucceeded.Should().BeTrue();

            // Check the error log and ruleset properties are set
            AssertErrorLogIsSetBySonarQubeTargets(result);
            AssertExpectedResolvedRuleset(result, "d:\\my.ruleset");

            AssertExpectedAdditionalFiles(result,
                                          result.GetCapturedPropertyValue(TargetProperties.ProjectConfFilePath),
                                          "should.not.be.removed.additional1.txt",
                                          "should.not.be.removed.additional2.txt",
                                          "c:\\config.1.txt",
                                          "c:\\config.2.txt");

            AssertExpectedAnalyzers(result,
                                    "c:\\data\\new.analyzer1.dll",
                                    "c:\\new.analyzer2.dll");

            AssertWarningsAreNotTreatedAsErrorsNorIgnored(result);
        }
コード例 #4
0
        public BuildLog Execute_Roslyn_Settings_ValidSetup(bool isTestProject, string msBuildLanguage)
        {
            // Arrange

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

            // Create a valid config file containing analyzer settings for both VB and C#
            var config = new AnalysisConfig
            {
                SonarQubeHostUrl  = "http://sonarqube.com",
                SonarQubeVersion  = "7.3", // legacy behaviour i.e. overwrite existing analyzer settings
                AnalyzersSettings = new List <AnalyzerSettings>
                {
                    // C#
                    new AnalyzerSettings
                    {
                        Language                   = "cs",
                        RuleSetFilePath            = "d:\\my.ruleset.cs",
                        TestProjectRuleSetFilePath = "d:\\my.ruleset.cs.test",
                        AnalyzerPlugins            = new List <AnalyzerPlugin>
                        {
                            new AnalyzerPlugin("csharp", "v1", "resName", new string [] { "c:\\1\\SonarAnalyzer.CSharp.dll", "c:\\1\\SonarAnalyzer.dll", "c:\\1\\Google.Protobuf.dll" }),
                            new AnalyzerPlugin("securitycsharpfrontend", "v1", "resName", new string [] { "c:\\2\\SonarAnalyzer.Security.dll", "c:\\2\\Google.Protobuf.dll" })
                        },
                        AdditionalFilePaths = new List <string> {
                            "c:\\config.1.txt", "c:\\config.2.txt"
                        }
                    },

                    // VB
                    new AnalyzerSettings
                    {
                        Language                   = "vbnet",
                        RuleSetFilePath            = "d:\\my.ruleset.vb",
                        TestProjectRuleSetFilePath = "d:\\my.ruleset.test.vb",
                        AnalyzerPlugins            = new List <AnalyzerPlugin>
                        {
                            new AnalyzerPlugin("vbnet", "v1", "resName", new string [] { "c:\\0\\SonarAnalyzer.VisualBasic.dll", "c:\\0\\Google.Protobuf.dll" }),
                            new AnalyzerPlugin("notVB", "v1", "resName", new string [] { "c:\\config.analyzer2.vb.dll" })
                        },
                        AdditionalFilePaths = new List <string> {
                            "c:\\config.1.txt", "c:\\config.2.txt"
                        }
                    }
                }
            };

            // Create the project
            var projectSnippet  = $@"
<PropertyGroup>
    <Language>{msBuildLanguage}</Language>
    <SonarQubeTestProject>{isTestProject.ToString()}</SonarQubeTestProject>
    <ResolvedCodeAnalysisRuleset>c:\\should.be.overridden.ruleset</ResolvedCodeAnalysisRuleset>
</PropertyGroup>

<ItemGroup>
    <Analyzer Include='project.additional.analyzer1.dll' />
    <Analyzer Include='c:\project.additional.analyzer2.dll' />
    <AdditionalFiles Include='project.additional.file.1.txt' />
    <AdditionalFiles Include='x:\aaa\project.additional.file.2.txt' />
</ItemGroup>
";
            var projectFilePath = CreateProjectFile(config, projectSnippet);

            // Act
            var result = BuildRunner.BuildTargets(TestContext, projectFilePath,
                                                  TargetConstants.OverrideRoslynAnalysisTarget);

            // Assert - check invariants
            result.AssertTargetExecuted(TargetConstants.OverrideRoslynAnalysisTarget);
            result.AssertTargetExecuted(TargetConstants.SetRoslynAnalysisPropertiesTarget);
            result.AssertTaskExecuted("GetAnalyzerSettings");
            result.BuildSucceeded.Should().BeTrue();

            AssertErrorLogIsSetBySonarQubeTargets(result);
            AssertWarningsAreNotTreatedAsErrorsNorIgnored(result);

            return(result);
        }
コード例 #5
0
        public void E2E_BareProject_CorrectlyCategorised()
        {
            // Checks that projects that don't include the standard managed targets are still
            // processed correctly e.g. can be excluded, marked as test projects etc

            // Arrange
            var rootInputFolder  = TestUtils.CreateTestSpecificFolderWithSubPaths(TestContext, "Inputs");
            var rootOutputFolder = TestUtils.CreateTestSpecificFolderWithSubPaths(TestContext, "Outputs");

            var sqTargetFile    = TestUtils.EnsureAnalysisTargetsExists(TestContext);
            var projectFilePath = Path.Combine(rootInputFolder, "project.txt");
            var projectGuid     = Guid.NewGuid();

            var projectXml  = @"<?xml version='1.0' encoding='utf-8'?>
<Project ToolsVersion='12.0' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>

  <PropertyGroup>
    <SonarQubeExclude>true</SonarQubeExclude>
    <Language>my.language</Language>
    <ProjectTypeGuids>{4}</ProjectTypeGuids>

    <ProjectGuid>{0}</ProjectGuid>

    <SonarQubeTempPath>{1}</SonarQubeTempPath>
    <SonarQubeOutputPath>{1}</SonarQubeOutputPath>
    <SonarQubeBuildTasksAssemblyFile>{2}</SonarQubeBuildTasksAssemblyFile>
  </PropertyGroup>

  <ItemGroup>
    <!-- no recognized content -->
  </ItemGroup>

  <Import Project='{3}' />

  <Target Name='Build'>
    <Message Importance='high' Text='In dummy build target' />
  </Target>

</Project>
";
            var projectRoot = BuildUtilities.CreateProjectFromTemplate(projectFilePath, TestContext, projectXml,
                                                                       projectGuid.ToString(),
                                                                       rootOutputFolder,
                                                                       typeof(WriteProjectInfoFile).Assembly.Location,
                                                                       sqTargetFile,
                                                                       TargetConstants.MsTestProjectTypeGuid
                                                                       );

            // Act
            var result = BuildRunner.BuildTargets(TestContext, projectRoot.FullPath,
                                                  TargetConstants.DefaultBuildTarget);

            // Assert
            result.BuildSucceeded.Should().BeTrue();

            result.AssertExpectedTargetOrdering(
                TargetConstants.DefaultBuildTarget,
                TargetConstants.CategoriseProjectTarget,
                TargetConstants.WriteFilesToAnalyzeTarget,
                TargetConstants.WriteProjectDataTarget);

            // Check the project info
            var projectInfo = ProjectInfoAssertions.AssertProjectInfoExists(rootOutputFolder, projectRoot.FullPath);

            projectInfo.IsExcluded.Should().BeTrue("Expecting the project to be marked as excluded");
            projectInfo.ProjectLanguage.Should().Be("my.language", "Unexpected project language");
            projectInfo.ProjectType.Should().Be(ProjectType.Test, "Project should be marked as a test project");
            projectInfo.AnalysisResults.Should().BeEmpty("Unexpected number of analysis results created");
        }
コード例 #6
0
        public void E2E_BareProject_FilesToAnalyze()
        {
            // Checks the integration targets handle non-VB/C# project types
            // that don't import the standard targets or set the expected properties
            // The project info should be created as normal and the correct files to analyze detected.

            // Arrange
            var context = CreateContext();

            var sqTargetFile    = TestUtils.EnsureAnalysisTargetsExists(TestContext);
            var projectFilePath = Path.Combine(context.InputFolder, "project.txt");
            var projectGuid     = Guid.NewGuid();

            var codeFile       = context.CreateInputFile("code.cpp");
            var contentFile    = context.CreateInputFile("code.js");
            var unanalysedFile = context.CreateInputFile("text.shouldnotbeanalysed");
            var excludedFile   = context.CreateInputFile("excluded.cpp");

            var projectXml  = @"<?xml version='1.0' encoding='utf-8'?>
<Project ToolsVersion='12.0' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>

  <PropertyGroup>
    <ProjectGuid>{0}</ProjectGuid>

    <SonarQubeTempPath>{1}</SonarQubeTempPath>
    <SonarQubeOutputPath>{1}</SonarQubeOutputPath>
    <SonarQubeBuildTasksAssemblyFile>{2}</SonarQubeBuildTasksAssemblyFile>
  </PropertyGroup>

  <ItemGroup>
    <ClCompile Include='{4}' />
    <Content Include='{5}' />
    <ShouldBeIgnored Include='{6}' />
    <ClCompile Include='{7}'>
      <SonarQubeExclude>true</SonarQubeExclude>
    </ClCompile>
  </ItemGroup>

  <Import Project='{3}' />

  <Target Name='Build'>
    <Message Importance='high' Text='In dummy build target' />
  </Target>

</Project>
";
            var projectRoot = BuildUtilities.CreateProjectFromTemplate(projectFilePath, TestContext, projectXml,
                                                                       projectGuid.ToString(),
                                                                       context.OutputFolder,
                                                                       typeof(WriteProjectInfoFile).Assembly.Location,
                                                                       sqTargetFile,
                                                                       codeFile,
                                                                       contentFile,
                                                                       unanalysedFile,
                                                                       excludedFile
                                                                       );

            // Act
            var result = BuildRunner.BuildTargets(TestContext, projectRoot.FullPath,
                                                  TargetConstants.DefaultBuildTarget);

            // Assert
            result.BuildSucceeded.Should().BeTrue();

            result.AssertExpectedTargetOrdering(
                TargetConstants.DefaultBuildTarget,
                TargetConstants.CategoriseProjectTarget,
                TargetConstants.WriteFilesToAnalyzeTarget,
                TargetConstants.WriteProjectDataTarget);

            // Check the content of the project info xml
            var projectInfo = ProjectInfoAssertions.AssertProjectInfoExists(context.OutputFolder, projectRoot.FullPath);

            projectInfo.ProjectGuid.Should().Be(projectGuid, "Unexpected project guid");
            projectInfo.ProjectLanguage.Should().BeNull("Expecting the project language to be null");
            projectInfo.IsExcluded.Should().BeFalse("Project should not be marked as excluded");
            projectInfo.ProjectType.Should().Be(ProjectType.Product, "Project should be marked as a product project");
            projectInfo.AnalysisResults.Should().HaveCount(1, "Unexpected number of analysis results created");

            // Check the correct list of files to analyze were returned
            var filesToAnalyze       = ProjectInfoAssertions.AssertAnalysisResultExists(projectInfo, AnalysisType.FilesToAnalyze.ToString());
            var actualFilesToAnalyze = File.ReadAllLines(filesToAnalyze.Location);

            actualFilesToAnalyze.Should().BeEquivalentTo(new string[] { codeFile, contentFile }, "Unexpected list of files to analyze");
        }
コード例 #7
0
        public void Roslyn_Settings_ValidSetup()
        {
            // Arrange

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

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

            var config = new AnalysisConfig();

            var analyzerSettings = new AnalyzerSettings
            {
                Language              = "cs",
                RuleSetFilePath       = "d:\\my.ruleset",
                AnalyzerAssemblyPaths = expectedAssemblies.ToList(),
                AdditionalFilePaths   = analyzerAdditionalFiles.ToList()
            };

            config.AnalyzersSettings = new List <AnalyzerSettings>
            {
                analyzerSettings
            };

            var configFilePath = Path.Combine(confDir, FileConstants.ConfigFileName);

            config.Save(configFilePath);

            // Create the project
            var properties = new WellKnownProjectProperties
            {
                SonarQubeConfigPath         = confDir,
                ResolvedCodeAnalysisRuleset = "c:\\should.be.overridden.ruleset"
            };

            var projectRoot = CreateValidProjectSetup(properties);

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

            var notRemovedAdditionalFiles = new string[] { "should.not.be.removed.additional1.txt", "should.not.be.removed.additional2.txt" };

            foreach (var notRemovedAdditionalFile in notRemovedAdditionalFiles)
            {
                projectRoot.AddItem(TargetProperties.AdditionalFilesItemType, notRemovedAdditionalFile);
            }

            projectRoot.Save(); // re-save the modified project

            // Act
            var result = BuildRunner.BuildTargets(TestContext, projectRoot.FullPath,
                                                  TargetConstants.OverrideRoslynAnalysisTarget);

            var projectSpecificConfFilePath   = result.GetCapturedPropertyValue(TargetProperties.ProjectConfFilePath);
            var expectedRoslynAdditionalFiles = new string[] { projectSpecificConfFilePath }
            .Concat(analyzerAdditionalFiles)
            .Concat(notRemovedAdditionalFiles)
            .ToArray();

            // Assert
            result.AssertTargetExecuted(TargetConstants.OverrideRoslynAnalysisTarget);
            result.AssertTargetExecuted(TargetConstants.SetRoslynAnalysisPropertiesTarget);
            result.BuildSucceeded.Should().BeTrue();

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

            AssertWarningsAreNotTreatedAsErrorsNorIgnored(result);
        }
コード例 #8
0
 public void NullArgsThrows()
 {
     Assert.Throws <ArgumentNullException>(() => BuildRunner.Execute(null, app => { }));
 }
コード例 #9
0
        public async Task <bool> BuildAsync(IConsole console, IProject project, string label = "", IEnumerable <string> definitions = null)
        {
            var builtProjects = new List <IProject>();

            var cancellationSouce = new CancellationTokenSource();

            IEnumerable <IProject> projects = new List <IProject> {
                project
            };

            projects = projects.Flatten(p => p.References);

            var toBuild = projects.ToList();

            using (var buildRunner = new BuildRunner())
            {
                console.WriteLine($"Creating: {Environment.ProcessorCount} build nodes.");
                await buildRunner.InitialiseAsync();

                var startTime = DateTime.Now;

                buildRunner.Start(cancellationSouce.Token, (node, proj) =>
                {
                    var netProject = proj as OmniSharpProject;

                    if (netProject.RestoreRequired)
                    {
                        var buildResult = netProject.Restore(console).GetAwaiter().GetResult();

                        if (!buildResult)
                        {
                            return(false);
                        }

                        netProject.MarkRestored();
                    }

                    if (RequiresBuilding(proj))
                    {
                        var result = node.BuildProject(proj).GetAwaiter().GetResult();

                        console.WriteLine();
                        console.WriteLine($"[{proj.Name}] Node = {node.Id}");

                        console.Write(result.consoleOutput);

                        if (result.result)
                        {
                            foreach (var output in result.outputAssemblies)
                            {
                                console.WriteLine($"{proj.Name} -> {output}");
                            }
                        }

                        return(result.result);
                    }

                    console.WriteLine($"[Skipped] {proj.Name} -> {proj.Executable}");

                    return(true);
                });

                var buildTasks = QueueItems(toBuild, builtProjects, buildRunner);

                bool canContinue = true;

                while (true)
                {
                    var result = await Task.WhenAny(buildTasks);

                    canContinue = result.Result.result;

                    buildTasks.Remove(result);

                    builtProjects.Add(result.Result.project);

                    if (canContinue)
                    {
                        if (toBuild.Count > 0)
                        {
                            buildTasks = buildTasks.Concat(QueueItems(toBuild, builtProjects, buildRunner)).ToList();
                        }

                        if (toBuild.Count == 0 && buildTasks.Count == 0)
                        {
                            break;
                        }
                    }
                    else
                    {
                        break;
                    }
                }

                cancellationSouce.Cancel();

                var duration = DateTime.Now - startTime;

                if (canContinue)
                {
                    console.WriteLine($"Build Successful - {duration.ToString()}");
                    return(true);
                }
                else
                {
                    console.WriteLine($"Build Failed - {duration.ToString()}");
                    return(false);
                }
            }
        }
コード例 #10
0
        private List <Task <(bool result, IProject project)> > QueueItems(List <IProject> toBuild, List <IProject> built, BuildRunner runner)
        {
            var tasks = new List <Task <(bool result, IProject project)> >();

            var toRemove = new List <IProject>();

            foreach (var item in toBuild)
            {
                bool canBuild = true;

                foreach (var dep in item.References.OfType <OmniSharpProject>())
                {
                    if (!built.Contains(dep))
                    {
                        canBuild = false;
                        break;
                    }
                }

                if (canBuild)
                {
                    toRemove.Add(item);
                    tasks.Add(runner.Queue(item));
                }
            }

            foreach (var item in toRemove)
            {
                toBuild.Remove(item);
            }

            return(tasks);
        }
コード例 #11
0
        private BuildLog Execute_E2E_TestProjects_ProtobufsUpdated(bool isTestProject, string projectSpecificSubDir)
        {
            // Protobuf files containing metrics information should be created for test projects.
            // However, some of the metrics files should be empty, as should the issues report.
            // See [MMF-485] : https://jira.sonarsource.com/browse/MMF-486
            // This method creates some non-empty dummy protobuf files during a build.
            // The caller can should check that the protobufs have been updated/not-updated,
            // as expected, depending on the type of the project being built.

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

            var code1 = CreateEmptyFile(rootInputFolder, "code1.cs");

            var projectXml      = $@"
<PropertyGroup>
  <SonarQubeTestProject>{isTestProject.ToString()}</SonarQubeTestProject>
</PropertyGroup>
<ItemGroup>
  <Compile Include='{code1}' />
</ItemGroup>

<!-- Target to create dummy, non-empty protobuf files. We can't do this from code since the targets create
     a unique folder. We have to insert this target into the build after the unique folder has been created,
     but before the targets that modify the protobufs are executed -->
<Target Name='CreateDummyProtobufFiles' DependsOnTargets='CreateProjectSpecificDirs' BeforeTargets='OverrideRoslynCodeAnalysisProperties'>

  <Error Condition=""$(ProjectSpecificOutDir)==''"" Text='Test error: ProjectSpecificOutDir is not set' />
  <Message Text='CAPTURE___PROPERTY___ProjectSpecificOutDir___$(ProjectSpecificOutDir)' Importance='high' />

  <!-- Write the protobufs to an arbitrary subdirectory under the project-specific folder. -->
  <MakeDir Directories='$(ProjectSpecificOutDir)\{projectSpecificSubDir}' />

  <WriteLinesToFile File='$(ProjectSpecificOutDir)\{projectSpecificSubDir}\encoding.pb' Lines='XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' />
  <WriteLinesToFile File='$(ProjectSpecificOutDir)\{projectSpecificSubDir}\file-metadata.pb' Lines='XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' />
  <WriteLinesToFile File='$(ProjectSpecificOutDir)\{projectSpecificSubDir}\metrics.pb' Lines='XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' />
  <WriteLinesToFile File='$(ProjectSpecificOutDir)\{projectSpecificSubDir}\symrefs.pb' Lines='XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' />
  <WriteLinesToFile File='$(ProjectSpecificOutDir)\{projectSpecificSubDir}\token-cpd.pb' Lines='XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' />
  <WriteLinesToFile File='$(ProjectSpecificOutDir)\{projectSpecificSubDir}\token-type.pb' Lines='XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' />
  
</Target>
";
            var projectFilePath = CreateProjectFile(projectXml, rootOutputFolder);

            // Act
            var result = BuildRunner.BuildTargets(TestContext, projectFilePath);

            // Assert
            result.AssertTargetSucceeded(TargetConstants.DefaultBuildTarget); // Build should succeed with warnings
            var projectSpecificOutputDir = CheckProjectSpecificOutputStructure(rootOutputFolder);

            // Sanity check that the above target was executed
            result.AssertTargetExecuted("CreateDummyProtobufFiles");

            var projectSpecificOutputDir2 = result.GetCapturedPropertyValue("ProjectSpecificOutDir");

            projectSpecificOutputDir2.Should().Be(projectSpecificOutputDir);

            AssertNoAdditionalFilesInFolder(projectSpecificOutputDir,
                                            ProtobufFileNames.Concat(new string[] { ExpectedAnalysisFilesListFileName, FileConstants.ProjectInfoFileName })
                                            .ToArray());

            return(result);
        }
コード例 #12
0
        public void E2E_HasAnalyzableFiles()
        {
            // Arrange
            var rootInputFolder  = TestUtils.CreateTestSpecificFolder(TestContext, "Inputs");
            var rootOutputFolder = TestUtils.CreateTestSpecificFolder(TestContext, "Outputs");

            // Mix of analyzable and non-analyzable files
            var none1    = CreateEmptyFile(rootInputFolder, "none1.txt");
            var foo1     = CreateEmptyFile(rootInputFolder, "foo1.txt");
            var foo2     = CreateEmptyFile(rootInputFolder, "foo2.txt");
            var content1 = CreateEmptyFile(rootInputFolder, "content1.txt");
            var code1    = CreateEmptyFile(rootInputFolder, "code1.txt");
            var bar1     = CreateEmptyFile(rootInputFolder, "bar1.txt");
            var junk1    = CreateEmptyFile(rootInputFolder, "junk1.txt");
            var content2 = CreateEmptyFile(rootInputFolder, "content2.txt");

            var projectXml      = $@"
<PropertyGroup>
  <ProjectGuid>4077C120-AF29-422F-8360-8D7192FA03F3</ProjectGuid>
</PropertyGroup>
<ItemGroup>
  <None Include='{none1}' />
  <Foo Include='{foo1}' />
  <Foo Include='{foo2}' />
  <Content Include='{content1}' />
  <Compile Include='{code1}' />
  <Bar Include='{bar1}' />
  <Junk Include='{junk1}' />
  <Content Include='{content2}' />
</ItemGroup>
";
            var projectFilePath = CreateProjectFile(projectXml, rootOutputFolder);

            // Act
            var result = BuildRunner.BuildTargets(TestContext, projectFilePath);

            // Assert
            result.AssertTargetSucceeded(TargetConstants.DefaultBuildTarget); // Build should succeed with warnings
            var projectSpecificOutputDir = CheckProjectSpecificOutputStructure(rootOutputFolder);

            // Check the list of files to be analyzed
            var expectedFilesToAnalyzeFilePath = AssertFileExists(projectSpecificOutputDir, ExpectedAnalysisFilesListFileName);
            var fileList = File.ReadLines(expectedFilesToAnalyzeFilePath);

            fileList.Should().BeEquivalentTo(new string []
            {
                rootInputFolder + "\\none1.txt",
                rootInputFolder + "\\content1.txt",
                rootInputFolder + "\\code1.txt",
                rootInputFolder + "\\content2.txt"
            });

            // Check the projectInfo.xml file points to the file containing the list of files to analyze
            var actualProjectInfo = CheckProjectInfoExists(projectSpecificOutputDir);

            var actualFilesToAnalyze = actualProjectInfo.AssertAnalysisResultExists("FilesToAnalyze");

            actualFilesToAnalyze.Location.Should().Be(expectedFilesToAnalyzeFilePath);

            actualProjectInfo.GetProjectGuidAsString().Should().Be("4077C120-AF29-422F-8360-8D7192FA03F3");

            AssertNoAdditionalFilesInFolder(projectSpecificOutputDir,
                                            ExpectedAnalysisFilesListFileName, FileConstants.ProjectInfoFileName);
        }
コード例 #13
0
ファイル: ScriptRunner.cs プロジェクト: flq/rfb
 public ScriptRunner Run()
 {
     var runner = new BuildRunner(setup);
       runner.Run();
       return this;
 }
コード例 #14
0
 public void NullInitializeThrows()
 {
     Assert.Throws <ArgumentNullException>(() => BuildRunner.Execute(Array.Empty <string>(), null !));
 }
コード例 #15
0
ファイル: GlobalsTester.cs プロジェクト: subdigital/Phantom
 public void Setup()
 {
     writer = new StringWriter();
     runner = new BuildRunner();
     Console.SetOut(writer);
 }
コード例 #16
0
 public void NullInitializeThrows()
 {
     Assert.Throws <ArgumentNullException>(() => BuildRunner.Execute(new string[0], null !));
 }
コード例 #17
0
ファイル: Build.cs プロジェクト: jvannoord/FacilityAspNet
    public static int Main(string[] args) => BuildRunner.Execute(args, build =>
    {
        var conformanceVersion = "2.0.2";

        var codegen = "fsdgenaspnet";

        var dotNetTools = new DotNetTools(Path.Combine("tools", "bin")).AddSource(Path.Combine("tools", "bin"));

        var dotNetBuildSettings = new DotNetBuildSettings
        {
            NuGetApiKey  = Environment.GetEnvironmentVariable("NUGET_API_KEY"),
            DocsSettings = new DotNetDocsSettings
            {
                GitLogin       = new GitLoginInfo("FacilityApiBot", Environment.GetEnvironmentVariable("BUILD_BOT_PASSWORD") ?? ""),
                GitAuthor      = new GitAuthorInfo("FacilityApiBot", "*****@*****.**"),
                GitBranchName  = Environment.GetEnvironmentVariable("APPVEYOR_REPO_BRANCH"),
                SourceCodeUrl  = "https://github.com/FacilityApi/FacilityAspNet/tree/master/src",
                ProjectHasDocs = name => !name.StartsWith("fsdgen", StringComparison.Ordinal),
            },
            DotNetTools        = dotNetTools,
            SourceLinkSettings = new SourceLinkSettings
            {
                ShouldTestPackage = name => !name.StartsWith("fsdgen", StringComparison.Ordinal),
            },
        };

        build.AddDotNetTargets(dotNetBuildSettings);

        build.Target("codegen")
        .DependsOn("build")
        .Describe("Generates code from the FSD")
        .Does(() => codeGen(verify: false));

        build.Target("verify-codegen")
        .DependsOn("build")
        .Describe("Ensures the generated code is up-to-date")
        .Does(() => codeGen(verify: true));

        build.Target("test")
        .DependsOn("verify-codegen");

        void codeGen(bool verify)
        {
            string verifyOption = verify ? "--verify" : null;

            var conformanceToolPath = dotNetTools.GetToolPath($"FacilityConformance/{conformanceVersion}");
            RunApp(conformanceToolPath, "fsd", "--output", "conformance/ConformanceApi.fsd", verifyOption);
            RunApp(conformanceToolPath, "json", "--output", "conformance/ConformanceTests.json", verifyOption);

            string configuration = dotNetBuildSettings.BuildOptions.ConfigurationOption.Value;
            string versionSuffix = $"cg{DateTime.UtcNow:yyyyMMddHHmmss}";
            RunDotNet("pack", Path.Combine("src", codegen, $"{codegen}.csproj"), "-c", configuration, "--no-build",
                      "--output", Path.GetFullPath(Path.Combine("tools", "bin")), "--version-suffix", versionSuffix);

            string packagePath     = FindFiles($"tools/bin/{codegen}.*-{versionSuffix}.nupkg").Single();
            string packageVersion  = Regex.Match(packagePath, @"[/\\][^/\\]*\.([0-9]+\.[0-9]+\.[0-9]+(-.+)?)\.nupkg$").Groups[1].Value;
            string codegenToolPath = dotNetTools.GetToolPath($"{codegen}/{packageVersion}");

            RunApp(codegenToolPath, "conformance/ConformanceApi.fsd", "conformance/WebApiControllerServer/Controllers",
                   "--namespace", "WebApiControllerServer.Controllers", "--newline", "lf", verifyOption);
            RunApp(codegenToolPath, "conformance/ConformanceApi.fsd", "conformance/CoreWebApiShimServer/Controllers",
                   "--namespace", "CoreWebApiShimServer.Controllers", "--target", "core", "--newline", "lf", verifyOption);
            RunApp(codegenToolPath, "conformance/ConformanceApi.fsd", "conformance/CoreControllerServer/Controllers",
                   "--namespace", "CoreControllerServer.Controllers", "--target", "core", "--newline", "lf", verifyOption);
        }
    });