Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable support for StaticCodeAnalysis.SuppressMessages.xml #643

Merged
merged 5 commits into from
Oct 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)"
ErikEJ marked this conversation as resolved.
Show resolved Hide resolved
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