Skip to content

Commit

Permalink
Enable support for StaticCodeAnalysis.SuppressMessages.xml (#643)
Browse files Browse the repository at this point in the history
* Enable support for StaticCodeAnalysis.SuppressMessages.xml to suppress rules for individual files

fixes #578

* fix typos

* fix more typos

* Set current dir

* fix space
  • Loading branch information
ErikEJ authored Oct 24, 2024
1 parent fed1206 commit 3fe3a62
Show file tree
Hide file tree
Showing 11 changed files with 121 additions and 4 deletions.
13 changes: 12 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -526,7 +526,18 @@ Static code analysis can be enabled by adding the `RunSqlCodeAnalysis` property
A xml file with the analysis results is created in the output folder.

The optional `CodeAnalysisRules` property allows you to disable individual rules or groups of rules.
The optional `CodeAnalysisRules` property allows you to disable individual rules or groups of rules for the entire project.

Starting with version 3.0.0 of the SDK, you can also disable rules per file. Add a `StaticCodeAnalysis.SuppressMessages.xml` file to the project root, with contents similar to this:

```xml
<?xml version="1.0" encoding="utf-8" ?>
<StaticCodeAnalysis version="2" xmlns="urn:Microsoft.Data.Tools.Schema.StaticCodeAnalysis">
<SuppressedFile FilePath="Procedures\sp_Test.sql">
<SuppressedRule Category="Microsoft.Rules.Data" RuleId="SR0001" />
</SuppressedFile>
</StaticCodeAnalysis>
```

Any rule violations found during analysis are reported as build warnings.

Expand Down
25 changes: 23 additions & 2 deletions src/DacpacTool/PackageAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,33 @@ public void Analyze(TSqlModel model, FileInfo outputFile, FileInfo[] analyzers)
settings.AssemblyLookupPath = string.Join(';', analyzers.Select(a => a.DirectoryName));
}

var projectDir = Environment.CurrentDirectory;
var suppressorPath = Path.Combine(projectDir, ProjectProblemSuppressor.SuppressionFilename);
List<SuppressedProblemInfo> suppressedProblems = new();

if (File.Exists(suppressorPath))
{
_console.WriteLine($"Using suppressor file: {suppressorPath}");
var problemSuppressor = ProjectProblemSuppressor.CreateSuppressor(projectDir);

suppressedProblems = problemSuppressor.GetSuppressedProblems().ToList();

foreach (var problem in suppressedProblems)
{
_console.WriteLine($"Suppressing rule: '{problem.Rule.RuleId}' in '{problem.SourceName}'");
}
}

var service = factory.CreateAnalysisService(model, settings);

if (_ignoredRules.Count > 0 || _ignoredRuleSets.Count > 0)
if (_ignoredRules.Count > 0
|| _ignoredRuleSets.Count > 0
|| suppressedProblems.Count > 0)
{
service.SetProblemSuppressor(p =>
_ignoredRules.Contains(p.Rule.RuleId)
suppressedProblems.Any(s => s.Rule.RuleId == p.Rule.RuleId
&& Path.Combine(projectDir, s.SourceName) == p.Problem.SourceName)
|| _ignoredRules.Contains(p.Rule.RuleId)
|| _ignoredRuleSets.Any(s => p.Rule.RuleId.StartsWith(s, StringComparison.OrdinalIgnoreCase)));
}

Expand Down
1 change: 1 addition & 0 deletions src/MSBuild.Sdk.SqlProj/Sdk/Sdk.targets
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,7 @@
<!-- Run it, except during design-time builds -->
<Message Importance="Low" Text="Running command: $(DacpacToolCommand)" />
<Exec Command="$(DacpacToolCommand)"
WorkingDirectory="$(ProjectDir)"
Condition="'$(DesignTimeBuild)' != 'true' AND '$(BuildingProject)' == 'true'"/>

<!-- Copy any referenced .dacpac packages to the output folder -->
Expand Down
15 changes: 15 additions & 0 deletions test/DacpacTool.Tests/DacpacTool.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,28 @@
<LangVersion>9.0</LangVersion>
</PropertyGroup>

<ItemGroup>
<None Remove="StaticCodeAnalysis.SuppressMessages.xml" />
<None Remove="Suppression\proc1.sql" />
<None Remove="Suppression\proc2.sql" />
</ItemGroup>

<ItemGroup>
<Content Include="SqlServer.Dac.dll">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="SqlServer.Rules.dll">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="Suppression\proc1.sql">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="Suppression\proc2.sql">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="Suppression\StaticCodeAnalysis.SuppressMessages.xml">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="TSQLSmellSCA.dll">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
Expand Down
40 changes: 39 additions & 1 deletion test/DacpacTool.Tests/PackageAnalyzerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -142,12 +142,50 @@ public void RunsAnalyzerWithoutAdditionalAnalyzers()
testConsole.Lines.ShouldContain($"Successfully analyzed package '{result.fileInfo.FullName}'");
}

[TestMethod]
public void RunsAnalyzerWithSuppressionFile()
{
// Arrange
var testConsole = (TestConsole)_console;
testConsole.Lines.Clear();
var path = new FileInfo(Path.GetTempFileName() + ".dacpac");

var packageBuilder = new PackageBuilder(testConsole);
packageBuilder.UsingVersion(SqlServerVersion.Sql150);
packageBuilder.AddInputFile(new FileInfo("./Suppression/proc1.sql"));
packageBuilder.AddInputFile(new FileInfo("./Suppression/proc2.sql"));
packageBuilder.SetMetadata("TestSuppression", "1.0.0");

packageBuilder.ValidateModel();
packageBuilder.SaveToDisk(path);

var packageAnalyzer = new PackageAnalyzer(_console, null);

try
{
//Set the current directory.
Directory.SetCurrentDirectory(Path.Combine(Path.GetDirectoryName(typeof(PackageAnalyzerTests).Assembly.Location), "Suppression"));
// Act
packageAnalyzer.Analyze(packageBuilder.Model, path, Array.Empty<FileInfo>());
}
finally
{
//Reset the current directory.
Directory.SetCurrentDirectory(Path.GetDirectoryName(typeof(PackageAnalyzerTests).Assembly.Location));
}

// Assert
testConsole.Lines.Count.ShouldBe(25);

testConsole.Lines.Count(l => l.Contains("Warning SR0001 : Microsoft.Rules.Data")).ShouldBe(1);
}

private static (FileInfo fileInfo, TSqlModel model) BuildSimpleModel()
{
var tmodel = new TestModelBuilder()
.AddTable("TestTable", ("Column1", "nvarchar(100)"))
.AddStoredProcedure("sp_GetData", "SELECT * FROM dbo.TestTable", "proc1.sql");

var model = tmodel.Build();
var packagePath = tmodel.SaveAsPackage();

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<StaticCodeAnalysis version="2" xmlns="urn:Microsoft.Data.Tools.Schema.StaticCodeAnalysis">
<SuppressedFile FilePath="proc1.sql">
<SuppressedRule Category="Microsoft.Rules.Data" RuleId="SR0001" />
</SuppressedFile>
</StaticCodeAnalysis>
5 changes: 5 additions & 0 deletions test/DacpacTool.Tests/Suppression/proc1.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
CREATE PROCEDURE [dbo].[sp_Test]
AS
BEGIN
SELECT * FROM [dbo].[MyTable];
END
5 changes: 5 additions & 0 deletions test/DacpacTool.Tests/Suppression/proc2.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
CREATE PROCEDURE [dbo].[sp_TestUnsuppressed]
AS
BEGIN
SELECT * FROM [dbo].[MyTable];
END
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
CREATE PROCEDURE [dbo].[sp_TestUnsuppressed]
AS
BEGIN
SELECT * FROM [dbo].[MyTable];
END
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<StaticCodeAnalysis version="2" xmlns="urn:Microsoft.Data.Tools.Schema.StaticCodeAnalysis">
<SuppressedFile FilePath="Procedures\sp_Test.sql">
<SuppressedRule Category="Microsoft.Rules.Data" RuleId="SR0001" />
</SuppressedFile>
</StaticCodeAnalysis>
4 changes: 4 additions & 0 deletions test/TestProjectWithAnalyzers/TestProjectWithAnalyzers.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@
<RunSqlCodeAnalysis>true</RunSqlCodeAnalysis>
</PropertyGroup>

<ItemGroup>
<None Remove="Procedures\sp_TestUnsuppressed.sql" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="ErikEJ.DacFX.SqlServer.Rules" Version="1.1.0" />
</ItemGroup>
Expand Down

0 comments on commit 3fe3a62

Please sign in to comment.