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

Update code to use 'var' where type is explicit. #2817

Merged
merged 5 commits into from
Jul 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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
19 changes: 11 additions & 8 deletions scripts/BuildAndTest.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ function Invoke-DotNetBuild($solutionFileRelativePath) {
Write-Information "Building $solutionFileRelativePath..."

$solutionFilePath = Join-Path $SourceRoot $solutionFileRelativePath
& dotnet build $solutionFilePath --configuration $Configuration --verbosity $BuildVerbosity --no-incremental -bl -p:WarningsAsErrors="MSB3277"
& dotnet build $solutionFilePath --configuration $Configuration --verbosity $BuildVerbosity --no-incremental -bl -p:WarningsAsErrors="MSB3277" /p:EnforceCodeStyleInBuild=true
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

EnforceCodeStyleInBuild

Internet query informed me that EnforceCodeStyleInBuild as expressed in csproj files only works within the IDE. For CLI builds you need to explicitly set this property (which appears to be a bit of a hammer, i.e., it will be applied everywhere. Fortunately that's what we want).


if ($LASTEXITCODE -ne 0) {
Exit-WithFailureMessage $ScriptName "Build of $solutionFilePath failed."
Expand Down Expand Up @@ -199,13 +199,16 @@ if (-not $NoRestore) {
}
}

if (-not $NoObjectModel) {
# Generate the SARIF object model classes from the SARIF JSON schema.
dotnet msbuild /verbosity:minimal /target:BuildAndInjectObjectModel $SourceRoot\Sarif\Sarif.csproj /fileloggerparameters:Verbosity=detailed`;LogFile=CodeGen.log
if ($LASTEXITCODE -ne 0) {
Exit-WithFailureMessage $ScriptName "SARIF object model generation failed."
}
}
# The SARIF object model is stable. We disable autogenerating it to allow
# for strict control enforcing style guidelines from command-line builds.
#if (-not $NoObjectModel) {
# # Generate the SARIF object model classes from the SARIF JSON schema.
# dotnet msbuild /verbosity:minimal /target:BuildAndInjectObjectModel $SourceRoot\Sarif\Sarif.csproj /fileloggerparameters:Verbosity=detailed`;LogFile=CodeGen.log
# if ($LASTEXITCODE -ne 0) {
# Exit-WithFailureMessage $ScriptName "SARIF object model generation failed."
# }
#}


if (-not $?) {
Exit-WithFailureMessage $ScriptName "BeforeBuild failed."
Expand Down
4 changes: 3 additions & 1 deletion src/.editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,7 @@ csharp_style_prefer_local_over_anonymous_function = true:suggestion
dotnet_diagnostic.SA1602.severity = suggestion
dotnet_diagnostic.SA1307.severity = silent
csharp_style_implicit_object_creation_when_type_is_apparent = true:suggestion
csharp_style_prefer_primary_constructors = true:suggestion
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

true

interestingly, this item was added when I explicitly used 'dotnet format' to get all autofixes I could from the command-line. This must be a tool feature, to add new diagnostics as they are added to the toolchain.


[*Tests.cs]

Expand All @@ -323,4 +324,5 @@ dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion
dotnet_style_prefer_compound_assignment = true:suggestion
dotnet_style_prefer_simplified_interpolation = true:suggestion
dotnet_style_namespace_match_folder = true:suggestion
dotnet_code_quality_unused_parameters = all:error
dotnet_code_quality_unused_parameters = all:error
dotnet_style_prefer_collection_expression = when_types_loosely_match:suggestion
6 changes: 3 additions & 3 deletions src/Sarif.Converters/AndroidStudioConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public override void Convert(Stream input, IResultLogWriter output, OptionallyEm

LogicalLocations.Clear();

XmlReaderSettings settings = new XmlReaderSettings
var settings = new XmlReaderSettings
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see csharp_style_var_when_type_is_apparent = true:error in the .editor config (

csharp_style_var_when_type_is_apparent = true:error
), but PRs prior to this are not failing the style check.

While this PR is a great cleanup, unless it's enforced in the PR check (https://github.com/microsoft/sarif-sdk/pull/2817/checks), the inconsistent style is going to creep back in.

This is likely due to EnforceCodeStyleInBuild missing in csproj/props: https://learn.microsoft.com/en-us/community/content/how-to-enforce-dotnet-format-using-editorconfig-github-actions

Consider fixing that in this PR, too.

{
IgnoreWhitespace = true,
IgnoreComments = true,
Expand All @@ -61,7 +61,7 @@ public override void Convert(Stream input, IResultLogWriter output, OptionallyEm
};

IList<Result> results;
using (XmlReader xmlReader = XmlReader.Create(input, settings))
using (var xmlReader = XmlReader.Create(input, settings))
{
results = ProcessAndroidStudioLog(xmlReader);
}
Expand Down Expand Up @@ -244,7 +244,7 @@ private static void SetSarifResultPropertiesForProblem(Result result, AndroidStu

private static string GenerateFullMessage(string description, ImmutableArray<string> hints)
{
StringBuilder sb = new StringBuilder();
var sb = new StringBuilder();
sb.Append(description);
foreach (string hint in hints)
{
Expand Down
2 changes: 1 addition & 1 deletion src/Sarif.Converters/AndroidStudioProblem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ public static AndroidStudioProblem Parse(XmlReader reader, AndroidStudioStrings
throw reader.CreateException(ConverterResources.AndroidStudioNotProblemElement);
}

Builder b = new Builder();
var b = new Builder();
if (!reader.IsEmptyElement)
{
int problemDepth = reader.Depth;
Expand Down
6 changes: 3 additions & 3 deletions src/Sarif.Converters/ClangAnalyzerConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public override void Convert(Stream input, IResultLogWriter output, OptionallyEm

try
{
XmlReaderSettings settings = new XmlReaderSettings
var settings = new XmlReaderSettings
{
IgnoreWhitespace = true,
DtdProcessing = DtdProcessing.Ignore,
Expand All @@ -46,7 +46,7 @@ public override void Convert(Stream input, IResultLogWriter output, OptionallyEm

var results = new List<Result>();

using (XmlReader xmlReader = XmlReader.Create(input, settings))
using (var xmlReader = XmlReader.Create(input, settings))
{
xmlReader.MoveToContent();
xmlReader.ReadStartElement(ClangSchemaStrings.PlistName);
Expand Down Expand Up @@ -179,7 +179,7 @@ private Result CreateResult(IDictionary<string, object> issueData)

private static IList<object> ReadArray(XmlReader xmlReader)
{
List<object> list = new List<object>();
var list = new List<object>();
bool readerMoved = false; // ReadElementContentAsString moves the reader so prevent double moves.

xmlReader.Read(); // Read past the "array" element start.
Expand Down
18 changes: 9 additions & 9 deletions src/Sarif.Converters/ClangTidyConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public override void Convert(Stream input, IResultLogWriter output, OptionallyEm
using var textReader = new StreamReader(input);
ClangTidyReport report = deserializer.Deserialize<ClangTidyReport>(textReader);

List<ClangTidyConsoleDiagnostic> logs = new List<ClangTidyConsoleDiagnostic>();
var logs = new List<ClangTidyConsoleDiagnostic>();
if (report != null)
{
string reportPath = (input as FileStream)?.Name;
Expand Down Expand Up @@ -78,7 +78,7 @@ private void AddLineNumberAndColumnNumber(ClangTidyReport report, List<ClangTidy

private List<ClangTidyConsoleDiagnostic> LoadLogFile(string logFilePath)
{
List<ClangTidyConsoleDiagnostic> returnValue = new List<ClangTidyConsoleDiagnostic>();
var returnValue = new List<ClangTidyConsoleDiagnostic>();

var logLines = File.ReadAllLines(logFilePath).ToList();
foreach (string line in logLines)
Expand All @@ -91,7 +91,7 @@ private List<ClangTidyConsoleDiagnostic> LoadLogFile(string logFilePath)
int columnNumber;
if (int.TryParse(match.Groups[2].Value, out lineNumber) && int.TryParse(match.Groups[3].Value, out columnNumber))
{
ClangTidyConsoleDiagnostic consoleDiagnostic = new ClangTidyConsoleDiagnostic()
var consoleDiagnostic = new ClangTidyConsoleDiagnostic()
{
LineNumber = lineNumber,
ColumnNumber = columnNumber
Expand All @@ -108,7 +108,7 @@ internal static Result CreateResult(ClangTidyDiagnostic entry)
{
entry = entry ?? throw new ArgumentNullException(nameof(entry));

Result result = new Result()
var result = new Result()
{
RuleId = entry.DiagnosticName,
Message = new Message { Text = entry.DiagnosticMessage.Message },
Expand All @@ -118,14 +118,14 @@ internal static Result CreateResult(ClangTidyDiagnostic entry)
// no level infomation in Clang-Tidy report
result.Level = FailureLevel.Warning;

Region region = new Region()
var region = new Region()
{
CharOffset = entry.DiagnosticMessage.FileOffset,
StartLine = entry.DiagnosticMessage.LineNumber,
StartColumn = entry.DiagnosticMessage.ColumnNumber,
};

Uri analysisTargetUri = new Uri(entry.DiagnosticMessage.FilePath, UriKind.RelativeOrAbsolute);
var analysisTargetUri = new Uri(entry.DiagnosticMessage.FilePath, UriKind.RelativeOrAbsolute);

var physicalLocation = new PhysicalLocation
{
Expand All @@ -136,7 +136,7 @@ internal static Result CreateResult(ClangTidyDiagnostic entry)
Region = region
};

Location location = new Location()
var location = new Location()
{
PhysicalLocation = physicalLocation
};
Expand All @@ -152,7 +152,7 @@ internal static Result CreateResult(ClangTidyDiagnostic entry)

foreach (ClangTidyReplacement fix in entry.DiagnosticMessage.Replacements)
{
Replacement replacement = new Replacement();
var replacement = new Replacement();

replacement.DeletedRegion = new Region
{
Expand Down Expand Up @@ -180,7 +180,7 @@ internal static Result CreateResult(ClangTidyDiagnostic entry)
Replacements = replacements
};

Fix sarifFix = new Fix(description: null, artifactChanges: new List<ArtifactChange>() { sarifFileChange }, properties: null);
var sarifFix = new Fix(description: null, artifactChanges: new List<ArtifactChange>() { sarifFileChange }, properties: null);
result.Fixes = new List<Fix> { sarifFix };
}

Expand Down
34 changes: 17 additions & 17 deletions src/Sarif.Converters/ContrastSecurityConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -594,7 +594,7 @@ private Result ConstructFormsWithoutAutocompletePreventionResult(ContrastLogRead
if (KeyIsReservedPropertyName(key)) { continue; }

string jsonValue = properties[key];
JObject root = JObject.Parse(jsonValue);
var root = JObject.Parse(jsonValue);
string snippet = root["html"].Value<string>();

int snippetLength = snippet.Length;
Expand Down Expand Up @@ -1429,7 +1429,7 @@ private static void ReadFindings(SparseReader reader, object parent)

private void ReadFinding(SparseReader reader, object parent)
{
Context context = (Context)parent;
var context = (Context)parent;

string ruleId = reader.ReadAttributeString(SchemaStrings.AttributeRuleId);

Expand All @@ -1443,7 +1443,7 @@ private void ReadFinding(SparseReader reader, object parent)

private static void ReadRequest(SparseReader reader, object parent)
{
Context context = (Context)parent;
var context = (Context)parent;
context.ClearRequest();

string protocol = reader.ReadAttributeString(SchemaStrings.AttributeProtocol);
Expand All @@ -1458,13 +1458,13 @@ private static void ReadRequest(SparseReader reader, object parent)

private static void ReadBody(SparseReader reader, object parent)
{
Context context = (Context)parent;
var context = (Context)parent;
context.RequestBody = reader.ReadElementContentAsString();
}

private static void ReadHeaders(SparseReader reader, object parent)
{
Context context = (Context)parent;
var context = (Context)parent;
context.ClearHeaders();

reader.ReadChildren(SchemaStrings.ElementHeaders, parent);
Expand All @@ -1475,23 +1475,23 @@ private static void ReadH(SparseReader reader, object parent)
string name = reader.ReadAttributeString(SchemaStrings.AttributeName);
string value = reader.ReadAttributeString(SchemaStrings.AttributeValue);

Context context = (Context)parent;
var context = (Context)parent;
context.AddHeader(name, value);

reader.ReadChildren(SchemaStrings.ElementH, parent);
}

private static void ReadParameters(SparseReader reader, object parent)
{
Context context = (Context)parent;
var context = (Context)parent;
context.ClearParameters();

reader.ReadChildren(SchemaStrings.ElementParameters, parent);
}

private static void ReadEvents(SparseReader reader, object parent)
{
Context context = (Context)parent;
var context = (Context)parent;
context.Signature = null;
context.MethodEvent = null;
context.PropagationEvents = null;
Expand All @@ -1505,7 +1505,7 @@ private static void ReadPropagationEvent(SparseReader reader, object parent)
{
reader.ReadChildren(SchemaStrings.ElementPropagationEvent, parent);

Context context = (Context)parent;
var context = (Context)parent;
context.PropagationEvents = context.PropagationEvents ?? new List<ThreadFlowLocation>();
context.PropagationEvents.Add(context.CurrentThreadFlowLocation);
context.CurrentThreadFlowLocation = null;
Expand All @@ -1514,7 +1514,7 @@ private static void ReadPropagationEvent(SparseReader reader, object parent)

private static void ReadSignature(SparseReader reader, object parent)
{
Context context = (Context)parent;
var context = (Context)parent;
string signature = reader.ReadElementContentAsString();
context.Signature = CreateStackFrameFromSignature(signature);
}
Expand Down Expand Up @@ -1566,7 +1566,7 @@ private static void ReadArgs(SparseReader reader, object parent)

private void ReadProperties(SparseReader reader, object parent)
{
Context context = (Context)parent;
var context = (Context)parent;

if (!_readingProps)
{
Expand Down Expand Up @@ -1608,7 +1608,7 @@ private static void ReadP(SparseReader reader, object parent)
{
string value = reader.ReadAttributeString(SchemaStrings.AttributeValue);

Context context = (Context)parent;
var context = (Context)parent;
context.AddParameter(name, value);
}

Expand All @@ -1622,7 +1622,7 @@ private static void ReadReturn(SparseReader reader, object parent)

private static void ReadStack(SparseReader reader, object parent)
{
Context context = (Context)parent;
var context = (Context)parent;
Debug.Assert(context.CurrentThreadFlowLocation == null);
context.CurrentThreadFlowLocation = new ThreadFlowLocation
{
Expand All @@ -1644,14 +1644,14 @@ private static void ReadSources(SparseReader reader, object parent)

private static void ReadEvidence(SparseReader reader, object parent)
{
Context context = (Context)parent;
var context = (Context)parent;
string evidence = reader.ReadElementContentAsString();
context.RefineEvidence(evidence);
}

private static void ReadSource(SparseReader reader, object parent)
{
Context context = (Context)parent;
var context = (Context)parent;
string type = reader.ReadAttributeString(SchemaStrings.AttributeType);
string name = reader.ReadAttributeString(SchemaStrings.AttributeName);
context.Sources = context.Sources ?? new HashSet<Tuple<string, string>>();
Expand All @@ -1661,7 +1661,7 @@ private static void ReadSource(SparseReader reader, object parent)

private static void ReadFrame(SparseReader reader, object parent)
{
Context context = (Context)parent;
var context = (Context)parent;
string frame = reader.ReadElementContentAsString();
context.CurrentThreadFlowLocation.Stack.Frames.Add(CreateStackFrameFromSignature(frame));
}
Expand All @@ -1670,7 +1670,7 @@ private static void ReadMethodEvent(SparseReader reader, object parent)
{
reader.ReadChildren(SchemaStrings.ElementMethodEvent, parent);

Context context = (Context)parent;
var context = (Context)parent;
context.MethodEvent = context.CurrentThreadFlowLocation;
context.CurrentThreadFlowLocation = null;
context.Signature = null;
Expand Down
4 changes: 2 additions & 2 deletions src/Sarif.Converters/CppCheckConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,15 @@ public override void Convert(Stream input, IResultLogWriter output, OptionallyEm
throw new ArgumentNullException(nameof(output));
}

XmlReaderSettings settings = new XmlReaderSettings
var settings = new XmlReaderSettings
{
IgnoreWhitespace = true,
DtdProcessing = DtdProcessing.Ignore,
NameTable = _nameTable,
XmlResolver = null
};

using (XmlReader xmlReader = XmlReader.Create(input, settings))
using (var xmlReader = XmlReader.Create(input, settings))
{
ProcessCppCheckLog(xmlReader, output, dataToInsert);
}
Expand Down
6 changes: 3 additions & 3 deletions src/Sarif.Converters/FortifyConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public override void Convert(Stream input, IResultLogWriter output, OptionallyEm
string runDescription = null;
var results = new List<Result>();

using (XmlReader reader = XmlReader.Create(input, settings))
using (var reader = XmlReader.Create(input, settings))
{
while (reader.Read())
{
Expand All @@ -79,7 +79,7 @@ public override void Convert(Stream input, IResultLogWriter output, OptionallyEm
{
while (StringReference.AreEqual(reader.LocalName, _strings.Issue))
{
FortifyIssue fortify = FortifyIssue.Parse(reader, _strings);
var fortify = FortifyIssue.Parse(reader, _strings);
results.Add(ConvertFortifyIssueToSarifIssue(fortify));
}
}
Expand Down Expand Up @@ -122,7 +122,7 @@ public static Result ConvertFortifyIssueToSarifIssue(FortifyIssue fortify)
SarifUtilities.AddOrUpdateDictionaryEntry(result.PartialFingerprints, "InstanceId", fortify.InstanceId);
}

List<string> messageComponents = new List<string>();
var messageComponents = new List<string>();
if (fortify.Abstract != null)
{
messageComponents.Add(fortify.Abstract);
Expand Down
Loading
Loading